Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does c# ?? operator short circuit?

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?

like image 987
Tilendor Avatar asked Mar 15 '11 22:03

Tilendor


People also ask

What does for do in C?

The for statement lets you repeat a statement or compound statement a specified number of times. The body of a for statement is executed zero or more times until an optional condition becomes false.

Does C have do while?

The C do while statement creates a structured loop that executes as long as a specified condition is true at the end of each pass through the loop.

What does |= mean in C?

The ' |= ' symbol is the bitwise OR assignment operator.


2 Answers

Yes, it says so in the C# Language Specification (highlighting by me):

A null coalescing expression of the form a ?? b requires a to be of a nullable type or reference type. If a is non-null, the result of a ?? b is a; otherwise, the result is b. The operation evaluates b only if a is null.

like image 123
Heinzi Avatar answered Sep 29 '22 00:09

Heinzi


Yes, it short circuits.

class Program {     public static void Main()     {         string s = null;         string s2 = "Hi";         Console.WriteLine(s2 ?? s.ToString());     } } 

The above program outputs "Hi" rather than throwing a NullReferenceException.

like image 23
Dan Tao Avatar answered Sep 29 '22 01:09

Dan Tao