I have been coding in Java(Mainly) and .Net for a while.
What I found is that the || logical operator in .Net is different in result to the || operator in Java.
Lets look at the following Java code:
Object obj = null;
if(obj == null || obj.toString().isEmpty()){
System.out.println("Object is null");
}
The result of the code above will be:
Object is null
The reason for that is because obj == null is true and the second expression wasn’t evaluated. If it was, I would have received a java.lang.NullPointerException.
And if I used the single or (|) I would also received a NullPointerException (Both are evaluated).
My question is the following:
If the code was C#, I will always get a ObjectReferenceNotSet etc. exception because the obj value is null and the second expression is always evaluated (Regardless of the operator), meaning the result is different in C# than in Java.
If I would to change the C# code to work properly, I have to create two if statements.
Is there not an easier way to do this in C# to be similar to Java? (Keep it in one if with 2 expressions)
Thank you.
The
||operator in C# is short-circuiting, just like in Java. As is&&. The|and&operators are not short-circuiting, just like in Java.If your results are different, there is a bug in the code. Can you show us the offending C# please?
This works fine: