Search code examples
javac#null-check

Null check + dereference on the same line


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")
{
  //...
}

Solution

  • && 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.