Omu Omu - 27 days ago 17
C# Question

get value of a property o => o.Property1 , defined in lambda

I need to get the value of a property defined in a lambda

public static MvcHtmlString MyHelper<T, TProperty>(
this HtmlHelper<T> html,
Expression<Func<T, TProperty>> prop)
{
var value = \\ get the value of Prop1 (not the name "Prop1")
...
}


the intended usage is something like:

public class FooViewModel
{
public string Prop1 { get;set; }
}





<%@ Page ViewPage<FooViewModel> %>

<%=Html.MyHelper(o => o.Prop1) %>

Answer

Why do you need expression here? If you only want to have property value, Func<T, TProperty> is sufficient - it is like any other delegate, just invoke it:

public static MvcHtmlString MyHelper<T, TProperty>(
    this HtmlHelper<T> html,
    Func<T, TProperty> prop)
{
    var obj = // ??
    var value = prop(obj); \\ get the value of Prop1 (not the name "Prop1")
    ...
}

Where obj is the object from which you want to read the value (I can't see the object around your code).