Search code examples
c#propertiesfunc

Get property name from Func<t, T>


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
}

Solution

  • 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.