Search code examples
c#.netasp.net-mvc.net-core

Difference between checking null using ? Vs?


I've seen this pattern many times.

var image = @Model?.Image?.First();

Or

var cId = cust!.Id;

I usually get the prompt from Visual Studio/ReSharper to add ? Or ! In the code but I've understood ? Is used to check that object isn't null before going into the next section of code but I can't find any documentation or explanation on exactly what these are or called and why it makes VS/RS prompt to add these. I know I can declare code such as

int? MyInt = 1;

To make it nullable but trying to get a better understanding on ? And !.

Does anyone have any reference or explanation so I can understand between the two?

I've checked MSDN but since I don't know what this pattern is called in not finding anything related to this or if I do is targeting something else.


Solution

  • This:

    var image = @Model?.Image?.First();
    

    is functionally equivalent to this:

    SomeType? image = null;
    
    if (@Model != null && @Model.Image != null)
    {
        image = @Model.Image.First();
    }
    

    where SomeType is the return type of @Model.Image.First().

    The ! operator works something like a cast. When you cast, you don't actually change anything but you are telling the compiler that a reference will definitely refer to a specific type of object at run time so it is safe to access members of that type. The null-forgiving operator tells the compiler that a nullable reference will definitely refer to an object at run time so it is safe to access members of that object.