#1,202 – C# 6.0 – Null-Conditional Operator

One of the new features coming in C# 6.0 is the null-conditional operator.

If you have a reference-typed variable, it can have a null value or can refer to instance of the appropriate type.  You’ll often see the following pattern, checking for null before invoking a method on the object, to avoid a NullReferenceException.

            string sTest = DateTime.Now.Hour == 5 ? "Five" : null;

            // OLD: Check for null to avoid NullReferenceException
            string sLeft;
            if (sTest != null)
                sLeft = sTest.Substring(0, 1);

The null-conditional operator allows us to do the same check for null, but in a more concise manner.

            // NEW: Null-Conditional operator
            sLeft = sTest?.Substring(0, 1);

If sTest is non-null, the Substring method is called and the result is assigned to sLeft.  If sTest is null, the expression returns null, so a null value is assigned to sLeft.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #1,202 – C# 6.0 – Null-Conditional Operator

  1. Pingback: Dew Drop – October 13, 2014 (#1875) | Morning Dew

  2. Any idea if null-conditionally does `null == x` or `Object.ReferenceEquals(null, x)`?

    • Sean says:

      I believe that it uses the equality operator, i.e. x != null. In practice, I don’t think it matters. You’d only get a difference result from ReferenceEquals(null,x) if x’s type has overloaded equality and if it for some reason returned a different result when comparing itself to the null value. That would be pretty strange behavior from an overloaded equality operator when comparing against null. It’s also possible, I guess, that the equality operator would have some side-effect that you might want triggered. That would also be bad design. In any case, the new 6.0 syntax does appear to invoke the overloaded equality operator. See Reed’s answer at http://stackoverflow.com/questions/12465961/is-referenceequalsmyobject-null-better-practice-than-myobject-null

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: