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

Working with Asp.Net MVC for quite some time, but I am stuck in a very strange question. Every time I create a model, I use lambda expressions, for example:

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

Why does Asp.Net MVC use this type of architecture?

Why can't I pass a property using reflection?

Uses lambda expression faster? Because under the hoods, I think that to get the name of the property, he should use reflection.

+6
source share
2 answers

Lambda> Reflection

Using lambdas, you get:

  • Sort by time, strongly typed property selectors.
  • Refactoring is simplified with Visual Studio's built-in refactoring tools.

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

  • Type of property.
  • Property Object
  • Inspect property metadata.

Also, 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 ) 

This is an expression tree, not a regular lambda. This allows MVC (and, again, any API) to manipulate the expression to add more actions before calling it at run time, without reflection.

More about expression trees:

+9
source

My answer will not be popular.

I believe Lambda is 99% always the best choice for three reasons.

Firstly, there’s absolutely nothing wrong with assuming your developers are smart. Other answers have a fundamental premise that every developer, but you are stupid. Not this way.

Secondly, Lamdas (and others) are modern syntax - and tomorrow they will become more common than they are today. The project code should flow from current and emerging agreements.

Third, writing the "old fashioned way" code may seem easier for you, but it’s not so easy for the compiler. This is important; legacy approaches have little room for improvement as the compiler updates. Lambdas (et al.), Which rely on the compiler to extend them, may benefit as the compiler handles them better over time.

Summarizing:

  • Developers can handle this.
  • Everybody do it
  • There future potential

Again, I know this will not be a popular answer. And believe me, "Simple is the best" is also my mantra. Maintenance is an important aspect for any source. I understood. But I think that we overshadow reality with some rules of thumb.

+1
source

All Articles