In your example you can have TWO different causes for the NullReferenceException
:
- Value `user` is null;
- `user.FirstName` is null.
I assume you’ve checked already if user
is not null, so lets skip that one.
Now lets assume that user.FirstName
is null, what happens then?
The first condition string.IsNullOrWhiteSpace(user.FirstName)
will result to true
. Is this enough for the if-statement to execute the inner code block or should the second condition also be evaluated?
Lets take a look at this truth-table:
A && B = RESULT
--------------------
False False = False
False True = False
True False = False
True True = True
So when using the &&
-operator the total condition is only true when both subconditions are true. So when the first condition is true, the second one still needs to be evaluated. A simple translation of the truth-table according to C# would be (where ??? stands for: Don’t care):
A && B = RESULT
--------------------
False ??? = False
True False = False
True True = True
So when checking your second condition, the property user.FirstName.Length
is read, resulting in your NullReferenceException
.
How to prevent this. As other people have stated, you probably want to execute the code block when: The FirstName
is NULL OR Empty OR WhiteSpace OR larger than 64. Your current condition checks, basically, if FirstName is NULL AND larger than 64.
So… use the ||-operator:
if (string.IsNullOrWhiteSpace(user.FirstName) || !(user.FirstName.Length <= 64))
or more clear:
if (string.IsNullOrWhiteSpace(user.FirstName) || (user.FirstName.Length > 64))
The C# truth-table would be:
A || B = RESULT
--------------------
False False = False
False True = True
True ??? = True
In which you can cleary see the “short circuit” part.
solved Short-Circuit If Condition Does not work