Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use lambdas in ASP.NET MVC instead of reflection?

Working with Asp.Net MVC for quite some time now, but I am stuck on a very strange question. Everytime I create a model I make use of lambda expressions like:

@Html.EditorFor(model=>model.SomeProperty)

Why is Asp.Net MVC using such type of an architecture?

Why cant I just pass in a property using reflection?

Is using lambda expression faster? Because under the hoods what I think is that to get the property name it must be using the reflection.

like image 695
Parv Sharma Avatar asked Feb 08 '13 08:02

Parv Sharma


2 Answers

Lambda > Reflection

Using lambdas you get:

  • Design-time, strongly-typed property selectors.
  • Refactoring made easy using built-in Visual Studio refactoring tools.

Thanks to lambdas, any API can know a lot of things from the property selector:

  • The property type.
  • The object of the property.
  • Inspect property metadata.

In addition, check the method signature (http://msdn.microsoft.com/en-us/library/ee402949(v=vs.108).aspx):

public static MvcHtmlString EditorFor<TModel, TValue>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression
)

It's an expression tree rather than a regular lambda. This allows MVC (and again, any API) to manipulate the expression in order to add more behaviors prior to invoking it during run-time, without reflection emit.

Learn more about expression trees:

  • http://msdn.microsoft.com/en-us/library/bb397951.aspx
like image 162
Matías Fidemraizer Avatar answered Oct 19 '22 05:10

Matías Fidemraizer


My answer will not be popular.

I believe Lambda's are 99% always the better choice for three reasons.

First, there is ABSOLUTELY nothing wrong with assuming your developers are smart. Other answers have an underlying premise that every developer but you is stupid. Not so.

Second, Lamdas (et al) are a modern syntax - and tomorrow they will be more commonplace than they already are today. Your project's code should flow from current and emerging conventions.

Third, writing code "the old fashioned way" might seem easier to you, but it's not easier to the compiler. This is important, legacy approaches have little opportunity to be improved as the compiler is rev'ed. Lambdas (et al) which rely on the compiler to expand them can benefit as the compiler deals with them better over time.

To sum up:

  1. Developers can handle it
  2. Everyone is doing it
  3. There's future potential

Again, I know this will not be a popular answer. And believe me "Simple is Best" is my mantra, too. Maintenance is an important aspect to any source. I get it. But I think we are overshadowing reality with some cliché rules of thumb.

like image 1
Neel Avatar answered Oct 19 '22 05:10

Neel