I have some code snippet given as below:
Want to resolve this conditation by checking the type at runtime.
PropertyInfo pi = type.GetProperty("propertyName");
var expression = new Object(); // this give me error after expression runs!
// Want to resolve this conditation by checking the type at runtime.
if (pi.PropertyType == typeof(DateTime))
{
// Want to pass the generic type parameter which has a same type created at runtime by identifying the property type.
expression = BuildExpression<T, DateTime>(data, group.Member);
}
private Func<T, V> BuildExpression<T, V>(IEnumerable<T> items, string propertyName)
{
Type type = typeof(T);
PropertyInfo pi = type.GetProperty(propertyName);
Type PropertyType = pi.DeclaringType;
var parameter = Expression.Parameter(typeof(T), propertyName);
var cast = Expression.TypeAs(parameter, pi.DeclaringType);
var getterBody = Expression.Property(cast, pi);
var exp = Expression.Lambda<Func<T, V>>(getterBody, parameter);
return exp.Compile();
}
Problem: I have to write condition on type I have to check the type of property by reflection and then have to build the expression.
What I want: I want to check the runtime time the Type of property and want to build runtime Generic parameter of that type which is same as a property type.
Basically I want to remove the If
condition on type checking and What I want is, the code should automatically detect the property type
and pass the same type in Generic parameter argument
, so that I don't have to check with all the types with If
condition. Like for string, decimal, double etc..
Could you please do let me know that resolution as I want to check the property
type at runtime and want to create Generic parameter type
with the same type as property has.