How does C # calculate where "m" comes from (m => m.SomeProperty)?
For example, in an MVC application, I can use html helpers to create a label as follows:
@Html.LabelFor(m => m.ProductName) I did not declare the variable "m" anywhere, but the IDE automatically determines what I'm trying to do. This is somewhat confusing that the IDE knows more about my code than I do. I would like to fix it.
Basically I want to know how he knows how to reference my model.
EDIT: Thanks for all the answers.
So, "Html" is an instance of HtmlHelper. "Html" is a member of the ViewPage base class. Its value is set in the InitHelpers () method of the ViewPage base class. The HtmlHelper constructor displays the ViewContext ViewPage as a parameter. ViewContext knows which model I'm using. LabelFor is an extension method of the HtmlHelper class. And that is why the lambda expression knows how to refer to my model.
Points are connected. Thanks!
You need to read lambdas, but what happens is you pass a pointer to the LabelFor method. Because Html strongly typed ( HtmlHelper<TYourModelType> ) and LabelFor declared Func<TYourModelType, TValue> , the compiler (and IDE) can determine that m is an instance of your model type and therefore provides good IDE drop-down lists for members.
Sometimes people find it useful to compare other syntax options at your disposal. For example, this would be equally true:
Html.LabelFor(SomePropertyMethod); ... string SomePropertyMethod(TYourModelType model) { return model.SomeProperty; } You declared m ; what you posted is the lambda syntax (in the form of an expression). The part before => is the list of parameters for your lambda, and the part after => is the body.
In your case, you use the lambda expression. This is a shorthand for:
@Html.LabelFor(m => { return m.PropertyName; }); In any case, the parameter m here represents the value passed to the function.