-1

I have a class with 3 properties:

  public class person
   {
     public int age   {get; set;}
     public string adress {get; set;}
     ...
   }

Is there a way using reflection to get the types of the attribues saying I wanna have int and string

I tried using

typeof(person).GetProperty("age") 

but I did not succeeded to get int (ans string for the adress attribute)

Thank you in advance

ADyson
  • 57,178
  • 14
  • 51
  • 63
Blood-HaZaRd
  • 2,049
  • 2
  • 20
  • 43
  • 1
    These are not attributes, those are properties :) Also have you looked at [PropertyInfo.PropertyType](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.propertytype?view=net-6.0)? Maybe something along the lines of `typeof(person).GetProperty("age")?.PropertyType.Name`? – Trevor Mar 07 '22 at 13:57
  • @Trevor Thnks I did the modifications typeof(person).GetProperty("age")?.PropertyType.Name returns Nullable1 – Blood-HaZaRd Mar 07 '22 at 14:01
  • you're welcome, glad to help. – Trevor Mar 07 '22 at 14:01
  • 2
    Also this may help you as well [Using PropertyInfo to find out the property type](https://stackoverflow.com/questions/3723934/using-propertyinfo-to-find-out-the-property-type) – Trevor Mar 07 '22 at 14:02
  • @Trevor: Kind of but I found that I have to use 'typeof(Person).GetProperty("age").PropertyType == typeof(Nullable) But It cant retreive that automatically – Blood-HaZaRd Mar 07 '22 at 14:06
  • Depending on use case and or implementation of course, but it doesn't change how to get the property type. I assumed from your post you wanted the string representation of the types. If not you can drop the `.Name`. – Trevor Mar 07 '22 at 14:14
  • 1
    @Trevor I had to use something like Nullable.GetUnderlyingType(typeof(person).GetProperty("age").PropertyType).Name Sorry I figured out that I missed the int? age from the declaration – Blood-HaZaRd Mar 07 '22 at 14:17
  • It's ok, glad you've got it figured out. – Trevor Mar 07 '22 at 14:19

1 Answers1

0

You should be able to use the Name of the PropertyType property of the PropertyInfo object returned by GetProperty():

var t = typeof(person).GetProperty("age");
Console.WriteLine(t.PropertyType.Name);

returns

Int32

Live demo: https://dotnetfiddle.net/iZG5IG

Documentation:

ADyson
  • 57,178
  • 14
  • 51
  • 63