Looking for a clean way to discover the string name of a method in a type safe way.
Here is what I have for properties, but I’m having trouble figuring out how to do it for methods.
class Program
{
class Customer
{
public String Id { get; set; }
}
public static String GetPropertyName<T>(
Expression<Func<T, Object>> selector) where T : class
{
var expression = (MemberExpression)selector.Body;
return expression.Member.Name;
}
static void Main(string[] args)
{
String propertyName = GetPropertyName<Customer>(c => c.Id);
}
}
Pretty much by changing to:
with the notable exception that you will need an
Action<T>option to handlevoidmethods. You will have to supply dummy parameter values, of course – if you really want you can obtain those too.Actually, your existing code might not be robust; you may need to throw away a cast operation (to box the int to an object).