0

How can I get the property name from Func<T, TResult>?

There many posts how to get prop name but from Expression and not from Func

_resultViewModel.SelectMeasurement(si => si.Height, vm => vm.HeightImg); // this is usage... I need to get "Height"

public void SelectMeasurement(Func<ScanInfo, double> measurement, Func<ResultViewModel, ImageSource> image)
{
    //some stuff
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
demo
  • 6,038
  • 19
  • 75
  • 149

2 Answers2

2

You can't get "property name" from Func<T, TResult>, because there are no any "property" and any "name", when delegate is constructed.

Moreover, delegate can get its return value in some different way, instead of member access:

Func<Foo, string> = foo => "bar";

This differs from the expressions case (Expression<Func<T, TResult>>), because expressions represent some code, which could be compiled into delegate, and could be parsed.

Dennis
  • 37,026
  • 10
  • 82
  • 150
  • ok, thanks for reply. If i use ` Expression>`, how can i get `Func` from expression? – demo Nov 02 '15 at 12:20
  • 1
    @demo: you can compile it: `yourExpressionVar.Compile()`. Note, that it rather slow, and it is better to think about caching of results. – Dennis Nov 02 '15 at 12:27
0

If you know that you are going to work with simple delegates that are meant to access model properties then you can use a method similar to this:

private static string GetFuncPropertyName<T, TResult>(Expression<Func<T, TResult>> expr)
{
    if (expr.Body is not MemberExpression memberExpression)
        throw new ArgumentException($"The provided expression contains a {expr.GetType().Name} which is not supported. Only simple member accessors (fields, properties) of an object are supported.");
    return memberExpression.Member.Name;
}

You can pass regular lambda delegates into it:

private class MyClass { public string MyProperty { get; set; } }
...
var propertyName = GetFuncPropertyNameT<MyClass, string>(m => m.MyProperty);

If you are not sure, you will have to get the actual method body func.GetMethodInfo().GetMethodBody();, parse IL bytes to a string (which is a non-trivial task) and then interpret it. For reference you can look at: https://www.codeproject.com/articles/14058/parsing-the-il-of-a-method-body

rvnlord
  • 3,487
  • 3
  • 23
  • 32