Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading