Does c# ?? operator short circuit?

て烟熏妆下的殇ゞ 提交于 2019-12-04 22:16:06

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!