Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between inspection and evaluation?

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.

like image 202
G. LC Avatar asked Jan 02 '23 01:01

G. LC


2 Answers

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.

like image 164
Saeb Amini Avatar answered Jan 05 '23 18:01

Saeb Amini


Just want to add few things to Saeb Amini's answer.

  1. It's always good idea to check Microsoft reference source or one of the open source version of code available to get hint of how it is working behind the scene. Visit the source
  2. By Looking at the source you will see, the framework is not accessing the object it self but uses 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.

like image 39
Dipen Shah Avatar answered Jan 05 '23 19:01

Dipen Shah