← All articles

Fluent Func/Expression Reflector

A reader's cleaner take on getting property and method names via C# Expression/Func reflection, wrapped in a fluent, static NameOf<T> helper.

Donn Felker

Donn Felker

2009.02.12 · 1 min read

Lou commented on the last post about using Expression and Func as an expression tool and came up with a much better solution than I had.

I’m going to repost it here for everyone else to see in the RSS reader.

This is the test class of whom we’d like to get the property (and method) names.

public class Thing
{
public int Height { get; set; }
public int Zone(string foo) { return 5; }
public void Restore(string bar, string baaz) { }
}

This is the updated reflection class that is now static and represents a more fluid/fluent syntax:

public class NameOf<T>
{
public static string Property<TResult>(Expression<Func<T, TResult>> func)
{
return (func.Body as MemberExpression).Member.Name;
}
public static string Method<TResult>(Expression<Func<T, TResult>> func)
{
return (func.Body as MethodCallExpression).Method.Name;
}
public static string Method(Expression<Action<T>> func)
{
return (func.Body as MethodCallExpression).Method.Name;
}
}

And a simple example:

class Program
{
static void Main(string[] args)
{
var name1 = NameOf<Thing>.Property(x => x.Height);
var name2 = NameOf<Thing>.Method(x => x.Zone(null));
var name3 = NameOf<Thing>.Method(x => x.Restore(null, null));
}
}

A big thanks goes out to [Lou](http://www.whereslou.com\)!

Donn Felker

Written by Donn Felker

I've spent 25+ years shipping software, writing books, and running my own companies. I write about thinking clearly, working for yourself, and doing real work while AI rewrites the rules. New essays land here every week.

Get the newsletter

Keep reading