Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the value from an anonymous expression?

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.

like image 593
mynameiscoffey Avatar asked Apr 05 '11 19:04

mynameiscoffey


People also ask

Can an anonymous function return a value?

Return Value From Anonymous Function Here, we have assigned the anonymous function func(n1,n2 int) int to the sum variable. The function calculates the sum of n1 and n2 and returns it.

What will happen if you put a break statement inside the anonymous method?

break; cannot be used to exit methods, instead you need a return. And while inside a method your scope is limited to that method because it could have been called from anywhere. While inside the method there is no information on the calling scope and the code therefore does not know if there is a loop to break out of.

Can you pass an anonymous function as an argument to another function?

They're called anonymous functions because they aren't given a name in the same way as normal functions. Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.

What is the point of anonymous functions?

The advantage of an anonymous function is that it does not have to be stored in a separate file. This can greatly simplify programs, as often calculations are very simple and the use of anonymous functions reduces the number of code files necessary for a program.


1 Answers

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. 
like image 145
Tejs Avatar answered Sep 22 '22 07:09

Tejs