use this if it’s non-null, otherwise use this default – the ?? feature



This isn’t really “new”, just a reminder of a neat feature, especially for those of us used to doing something very similar.  It works great on Nullable<T> too!


using System;


 


class Program


{


    static void Main(string[] args)


    {


        int? realInt = 27;


        int? nullInt = null;


        string realString = “foo”;


        string nullString = null;


 


        int defaultInt = -1;


        string defaultString = “default”;


 


        Console.WriteLine(“realInt: {0}”, realInt ?? defaultInt);


        Console.WriteLine(“nullInt: {0}”, nullInt ?? defaultInt);


        Console.WriteLine(“realString: {0}”, realString ?? defaultString);


        Console.WriteLine(“nullString: {0}”, nullString ?? defaultString);


        // Output:


        //   realInt: 27


        //   nullInt: -1


        //   realString: foo


        //   nullString: default


    }


}


Comments (0)