سؤال

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