I need to turn an string that represents a property name on an interface into an expression. I have most of it working, there is just 1 piece that I can't figure out at the end.
static Expression<Func<T, int>> MakeGetter<T>(string propertyName)
{
var input = Expression.Parameter(typeof(T));
var property = typeof(T).GetProperty(propertyName) ??
GetProperty(propertyName, typeof(T));
var expr = Expression.Property(input, property);
var propType = property.PropertyType.Name;
switch (propType.ToLower())
{
case "string":
return Expression.Lambda<Func<T, string>>(expr, input);
case "int":
return Expression.Lambda<Func<T, int>>(expr, input);
}
}
private static PropertyInfo GetProperty(string propertyName, Type i)
{
var baseInterfaces = i.GetInterfaces();
foreach (var baseInterface in baseInterfaces)
{
var property = baseInterface.GetProperty(propertyName);
return property ?? GetProperty(propertyName, baseInterface);
}
return null;
}
The one problem that I have is at the end of the MakeGetter function I don't know if the function is a string or int or some other type and have no way of knowing until after I do all of the reflection, so how can I create this method, so that it is generic and will return an Expression correctly.