C# Fluent API Design: Get property name from a Func<T>

image

Have you ever wondered how all those cool fluent APIs use anonymous functions (Func<T>) to get property names?  We were building some helper extensions methods internally and had this exact need.  It wasn’t immediately clear how to accomplish this but after some research it wasn’t too complicated to understand.

Code

Basically you accept the Func<T> as an Expression<Func<T>>, then you have access to the expression metadata and can traverse the expression tree based on type to find the member name you are looking for.  Expressions can get MUCH more complicated but it’s not too bad in this case.  With some simple debugging you can figure out how to traverse the tree correctly.  UnaryExpression for example is used to represent integer values.

Expressions power LINQ (Language-INtegrated Query) in .NET and are a great way to kill a few weeks of research if you ever have the time. I once built an entire reporting UI in ASP.NET based on LINQ statements by reverse engineering their expression trees.  It was really hard and I’m not sure we could have maintained the code long term but it worked really well and was VERY cool in the end.

Here is the full code with usage examples – https://gist.github.com/rschiefer/24887b564901b205578dfbb32db95d66#file-fluenapidesign-getmembername_full-cs-L32-L44

Happy Tree Traversing!

Leave a Reply