user310616
user310616

Reputation: 79

HTML Helper lambda query

I had a query regarding how parameter types in a lambda expression are evaluated.

If we're querying an IEnumerable of type Customer and have a statement such as customers.Where(c => c.City == "London"), c is of type Customer.

In HTML Helpers used in ASP.NET MVC 3 if we have a statement like Html.TextBoxFor(c => c.Foo) in a strongly typed view, c is of type that the view is bound to.

What I don't understand is how the compiler and visual studio intellisense know the type of the parameters in the lambda. The MSDN documentation says "the compiler can infer the type based on the lambda body, the underlying delegate type, and other factors as described in the C# Language Specification". However I don't get how the lambda body or the delegate type allow the compiler to determine what the data type of the parameter is.

Cheers,

Upvotes: 1

Views: 233

Answers (2)

dknaack
dknaack

Reputation: 60438

Description

They know it because the method defines a Expression.

Sample

This method needs a expression that results in a property of type double

public static MvcHtmlString MethodName<TModel>(
    this HtmlHelper<TModel> instance, 
    TModel model, 
    Expression<Func<TModel,double>> selector)
{

}

More Information

Upvotes: 0

Richard
Richard

Reputation: 108975

If you look at the type of Html.TextBoxFor etc. you'll find the parameter1 isn't Func<TModel, TProperty> (a compiled delegate), but Expression<Func<TModel, TProperty>> which is actually a data structure from which a delegate can be compiled at runtime.

Or directly examined to see what it is doing. In this case to ensure that it is actually a field or property access expression, and then reading the name of the property to allow HTML to reference the name, before then getting a delegate to get the property's value.


1 As an extension method, the first parameter is the type it applies to, and the second declared parameter is the first parameter when declared.

Upvotes: 1

Related Questions