Does c# ?? operator short circuit?
Asked Answered
L

3

37

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?

Lytic answered 15/3, 2011 at 22:36 Comment(6)
Why don't you try it? Use your own method on the right-hand side.Sixfooter
I'm very sure it does. A lot of code I've seen would be broken otherwise. The MSDN article doesn't mention it, and I'm too lazy to look it up in the spec.Estevan
Because I wanted to know authoritatively(read: I'm lazy ;)Lytic
That's actually a good point. If you only try it, you can never be sure if the behavior you observe is (a) something you can always rely on or (b) just some implementation detail of the compiler (e.g. some optimization). To be on the safe side, you need to check the documentation for the specified behavior.Dinky
I see so many questions like this. Why does Google take me here rather than to the language specification? Google first took me here: msdn.microsoft.com/en-us/library/ms173224.aspx Why doesn't that page say answer the question about short circuiting?Hyposensitize
@Trade-IdeasPhilip: 1. Because the language specification is a Word file downloadable from the MS Download center and, thus, not Google-friendly. 2. Because sometimes SO is better than MSDN. ;-)Dinky
D
56

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.

Dinky answered 15/3, 2011 at 22:48 Comment(0)
P
18

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.

Pennsylvanian answered 15/3, 2011 at 22:38 Comment(0)
D
8

Yes.

    public Form1()
    {
        string string1 = "test" ?? test();
        MessageBox.Show(string1);
    }

    private string test()
    {
        MessageBox.Show("does not short circuit");
        return "test";
    }

If it did not short circuit, test() would be called and a messagebox would show that it "does not short circuit".

Directrix answered 15/3, 2011 at 22:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.