#1,203 – C# 6.0 – Using the Null-Conditional with Value Types

The new null-conditional allows checking for null and de-referencing a reference-typed variable in a single step.

            string sLeft = sTest?.Substring(0, 1);

If the variable being checked for null (e.g. sTest) is null, the result of the expression is null.  This works as expected if the result of the expression is being assigned to a reference-typed variable (e.g. sLeft).  If the method or property being invoked, however, is a value type, then the result of the expression must be a nullable type.

For example, we might do the following in C# 5.0:

            int sLen;
            if (sTest != null)
                sLen = sTest.Length;

If sTest is null, the assignment isn’t done and sLen retains its value.

In C# 6.0, you can do this assignment using the null-conditional.  The variable being assigned to must be a nullable type whose base type matches the type of the expression.

            int? sLen = sTest?.Length;
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #1,203 – C# 6.0 – Using the Null-Conditional with Value Types

  1. Pingback: Dew Drop – October 14, 2014 (#1876) | Morning Dew

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: