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.
Lambda > Reflection
Using lambdas you get:
Thanks to lambdas, any API can know a lot of things from the property selector:
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:
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With