Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does c# figure out where "m" comes from in (m => m.SomeProperty)?

For example, in an MVC app, I can use the Html helpers to create a label like this:

@Html.LabelFor(m => m.ProductName)

I haven't declared the variable "m" anywhere, but the IDE automatically figures out what I'm trying to do. It's somewhat disconcerting that the IDE knows more about my code than I do. I'd like to fix that.

I mostly want to know how it knows how to reference my model.

EDIT: Thanks for all of 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 takes the ViewContext of the ViewPage as a paramter. The ViewContext knows what model I'm using. The LabelFor is an extension method on the HtmlHelper class. And that's why the lambda expression knows how to reference my model.

Dots are connected. Thanks!

like image 595
Jim Avatar asked Dec 10 '22 12:12

Jim


2 Answers

You need to read up on lambdas, but what's going on is that you're passing in a function pointer to the LabelFor method. Because Html is strongly typed (HtmlHelper<TYourModelType>) and LabelFor is declared like Func<TYourModelType, TValue>, the compiler (and IDE) can determine that m is an instance of your model type, and hence provide nice IDE drop downs for the members.

Sometimes people find it helpful to compare the other syntactical options at your disposal. For example, this would be equally valid:

Html.LabelFor(SomePropertyMethod);

...

string SomePropertyMethod(TYourModelType model) 
{
    return model.SomeProperty;
}
like image 148
Kirk Woll Avatar answered Dec 29 '22 11:12

Kirk Woll


That is declared against your View at the top.

 <%@ Page Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.EntryForm1>" %>

So your form inherits from ViewPage and it would understand what type T is.

like image 36
Aliostad Avatar answered Dec 29 '22 11:12

Aliostad