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?

有帮助吗?

解决方案

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"
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top