When using the ??
operator in C#, does it short circuit if the value being tested is not null?
Example:
string test = null;
string test2 = test ?? "Default";
string test3 = test2 ?? test.ToLower();
Does the test3 line succeed or throw a null reference exception?
So another way to phrase the question: Will the right hand expression of the ?? operator get evaluated if the left hand is not null?
Yes, it says so in the C# Language Specification (highlighting by me):
A null coalescing expression of the form
a ?? b
requiresa
to be of a nullable type or reference type. Ifa
is non-null, the result ofa ?? b
isa
; otherwise, the result isb
. The operation evaluatesb
only ifa
is null.