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?
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With