I am going through the Razor tutorial on Microsoft Docs and came across a lambda expression used in an HTML helper:
@Html.DisplayNameFor(model => model.Movie[0].Title))
Movie is of type IList< Movie >, where Movie is a class created in the tutorial. The author states that:
"DisplayNameFor HTML Helper inspects the Title property referenced in the lambda expression to determine the display name. The lambda expression is inspected rather than evaluated. That means there is no access violation when Movie[0] is null or empty."
I understand inspection from intuition but how does this differ from say:
Console.WriteLine(Movie[0].Title)
if the HTML helper sees an empty List there is no issue but if the console method sees an empty list an exception will be thrown.
The only way I could guess at how this works is that behind the scenes there is a try / catch at work.
Display Name means either the name of the property itself, i.e. "Title"
, or the string value defined in the Display
attribute on the property, if the property has one, i.e.:
public class Movie
{
[Display(Name = "Movie Title")]
public string Title { get; set; }
}
We can see it doesn't care about the Title
property's value, so it never needs to evaluate it, therefore it won't throw if the movie is null.
Just want to add few things to Saeb Amini's answer.
Metadata
from the expression it self to get Display name of the property in expression so it will not result in any exception even if object is null.Finally, To answer your question, evaluation is when you actually evaluate lamda expression for the result (invocation) while inspection is when you inspect various attributes of the lamda expression.
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