Combining the coalescence more than once?

83 views Asked by At

Is there anything in C# that would allow you to do something such as

string str = nullval1 ?? nullval2 ?? nullval3 ?? "Hi";

and it would go left to right picking the first one that is not null?

If this operator doesnt do this, is there a possible alternative to provide similar function with minimal code?

1

There are 1 answers

4
Jon Skeet On BEST ANSWER

That works absolutely fine as-is. Sample code:

using System;

class Program
{
    static void Main(string[] args)
    {
        string x = null;
        string y = "y";
        string z = "z";

        Console.WriteLine(x ?? y ?? z); // Prints "y"
    }
}