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.
1
2
3
4
5
6
| 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.
1
2
| // 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.
Comments
Post a Comment