0

Are there any dangers in checking for null and dereferencing on the same line?

If myObj is in fact null, how would this code behave?

Are there differences in how different languages handle situations like these (ie C# vs Java)

For example, something like below

if(myObj != null && myObj.someProp == "Test")
{
  //...
}

2 Answers2

5

&& is short-circuiting so if myObj is indeed null then the second condition will never be evaluated.

This behaviour is the same for both C# and Java.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

In your example the if condition expect a boolean value that is provided by the boolean operation myObj != null && myObj.someProp == "Test".

When using the && operator the left operand is checked first. If its value equals true then the right operand is checked as it's not possible to know its state in advance. But if its value equals false then no need to check the right operand as no matter the right condition state will be, the whole operation will result to false. This is why it's safe.

But when using the & operator both operands are always checked. Your example would look as follows with the & operator:

if(myObj != null & myObj.someProp == "Test")
{
  //...
}

Doing so, when myObj variable is equals to null then the code above will fail. In this case your code won't be safe.

I hope this helps;