Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting property type with reflection

I have a little problem by getting the type of an Property by reflection.

I have a class which include only simple types like string, int, decimal...

public class simple 
{
  public string article { get; set; }
  public decimal price { get; set; }
}

Now I need to take this properties by reflection and handle them by it's type.

I need something like this:

Type t = obj.GetType();
PropertyInfo propInfo = t.GetProperty("article");
Type propType = ??  *GetPropType*() ??

switch (Type.GetTypeCode(propType))
{
  case TypeCode.Decimal:
    doSome1;
    break;
  case TypeCode.String:
    doSome2;
    break;
}

For strings it works to do propInfo.PropertyType.UnderlyingSystemType as GetPropType() but not for decimal for example.

For decimal works propInfo.PropertyType.GenericTypeArguments.FirstOrDefault(); but not for strings.

Hos can get the type for all simple types?

like image 976
Nunzio Avatar asked Sep 13 '25 22:09

Nunzio


1 Answers

You could use PropertyType to determine which is string or decimal. Try like this;

Type t = obj.GetType();
PropertyInfo propInfo = t.GetProperty("article");
if (propInfo.PropertyType == typeof(string))
{
    Console.WriteLine("String Type");
}
if (propInfo.PropertyType == typeof(decimal) 
    || propInfo.PropertyType == typeof(decimal?))
{
    Console.WriteLine("Decimal Type");
}
like image 69
lucky Avatar answered Sep 16 '25 13:09

lucky