开发者

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?


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.


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.


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".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜