Wednesday, September 24, 2014

?? Operator is great for defaulting objects

If you need to default an object, an easy way to do this is with the null-coalescing operator.  In this example I need to default MyTempClass if I cannot pull it from another location.

using System;

namespace Tips
{
    public class NullCoalescingOperator
    {
        public void RunTip()
        {
            MyTempClass myTempClass = null;
            MyTempClass myOtherTempClass = new MyTempClass()
            {
                MyProperty = 1
            };
            MyTempClass x = myTempClass ?? myOtherTempClass;
            Console.WriteLine("{0}", x.MyProperty);
        }
    }

    public class MyTempClass
    {
        public int MyProperty { get; set; }
    }
}

No comments:

Post a Comment