Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to check an object for null and in the same if-statement compare the object's property value?

Tags:

c#

.net

asp.net

See thread title. Can I safely do something like that without worrying about a NullReferenceException, or is not guaranteed that those boolean expressions will be evaluated left to right?

// can this throw an NRE?
if (obj == null || obj.property == value)
{
   // do something
}
like image 507
nw. Avatar asked Aug 11 '10 22:08

nw.


People also ask

Which of the following checks if the property is null?

To check if an object's properties have a value of null : Use the Object. values() method to get an array of the object's values.

What is null check in C#?

NULL checks in C# v.The question mark symbol which used in if condition, which means that it'll check whether value is NULL, if not then it'll check whether Name is null. Also, we can also do Null using Null Coalescing operator, Var test = value ?? “value is null”; C# Copy.


2 Answers

They will be evaluated left to right, guaranteed. So yes, its safe.

The conditional-OR operator (||) performs a logical-OR of its bool operands, but only evaluates its second operand if necessary.

http://msdn.microsoft.com/en-us/library/6373h346%28VS.71%29.aspx

like image 60
heisenberg Avatar answered Sep 23 '22 12:09

heisenberg


That's perfectly safe to do. If the first expression on the left is true, then the rest isn't evaluated.

like image 35
DavidGouge Avatar answered Sep 22 '22 12:09

DavidGouge