Functional Type member resolution with C#
An interesting problem cropped up today regarding reflection and how LINQ might make for a strongly typed solution. K. Scott Allen suggested a while back to use lambdas to remove the use of ‘magic’ strings in building Fetching Intentions used in NFetchSpec and it was suggested by my colleague Mark that a similar approach be used in resolving a types property name using strongly typed expressions. Given the following class:
public class Criteria { private int _pageCounter; public int PageCounter { get { return _pageCounter; } set { _pageCounter = value; } } private string _levels; public string Levels { get { return _levels; } set { _levels = value; } } }
I want to dynamically resolve any property name using an Expression such as:
Expression<Func<Criteria, string>> f = c => c.Levels;
After fumbling around for a while it occurred that functional programming was yet again the simplest way to approach this.
public class PropertyNameResolver<T> { public static string Resolve<TPropertyType> (Expression<Func<T, TPropertyType>> expression) { Func<Expression<Func<T, TPropertyType>>, string> prop_name_function = l => { int posDot = l.Body.ToString().LastIndexOf(“.”) + 1; return l.Body.ToString().Remove(0, posDot); }; var property_name = typeof(T).GetProperty(prop_name_function(expression)).Name; return property_name; } }
By supplying the expression and encapsulating the function that takes the expression as an argument, we get access to the body and parameters in the expression tree built by the original lambda and when be execute the outer function we can extrapolate the property name. Here’s an example of the usage:
var pc = PropertyNameResolver<Criteria>.Resolve<int>(c => c.PageCounter);
Console.WriteLine(pc);
Functional goodness in C#.


