How do I get the value from an anonymous expression?

mynameiscoffey picture mynameiscoffey · Apr 5, 2011 · Viewed 11.8k times · Source

For sake of simplicity, imagine the following code:

I want to create a Foo:

public class Foo
{
    public string Bar { get; set; }
}

And pass it to a special Html Helper method:

Html.SomeFunction(f => f.Bar);

Which is defined as:

public string SomeFunction<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)

I want to get the value of Bar inside of this function, but have absolutely no idea how to get it.

Answer

Tejs picture Tejs · Apr 5, 2011

Simply compile the expression and get the value.

Func<TModel, TValue> method = expression.Compile();

TValue value = method(html.ViewData.Model);
// might be a slightly different property, but you can get the ViewModel 
// from the HtmlHelper object.