C# 6.0 provides a new way of checking null values compared to its traditional ways.
In earlier versions, to avoid a nullpointerexception, we need to do null checking before invocation of a function.
C# 6.0 provides a null-conditional operator (?) that can be used to avoid writing redundant code every time a null check must be done.
However, developers need to be cautious about its usage and return a value assigned to variables. The null-conditional operator short-circuits the actual operation and performs a null check. The result of the short circuiting is NULL if the operand itself is null. Siince null values cannot be assigned to value types, using a null-conditional operator as shown below would throw a compile time error:
- string inputString="Mario";
- int length=inputString?.Length
- T? item = collection?[index];
- T? item = (collection != null) ? collection[index] : null.
Another common pattern where the null-conditional operator could be used is in combination with the coalesce operator. Instead of checking for null on docList before invoking Length, you can retrieve an item count as follows:
- List<string> docList = GetListOfDocuments("c:/temp/");
- return docList?.Count ?? 0;
Another highly awaited feature in the list is to check for null before invoking a delegate. Thanks to the Microsoft team because this problem has been persistent since C# 1.0 .
Traditional approach:
- public class Delegate_Example
- {
- public event EventHandler<float> OnPriceChanged;
- private int _price;
- public int Price
- {
- get
- {
- return _price;
- }
- set
- {
- EventHandler<float> localOnchanged = OnPriceChanged;
- if (localOnchanged!=null)
- {
- _price = value;
- localOnchanged(this, value);
- }
- }
- }
- }
- public class Delegate_Example
- {
- public event EventHandler<float> OnPriceChanged;
- private int _price;
- public int Price
- {
- get
- {
- return _price;
- }
- set
- {
- OnPriceChanged?.Invoke(this, value);
- }
- }
- }
- Short-circuit additional invocations in the call chain if the operand is null.
- Return null if the operand is null.
- Support invocation of dele in a thread safe manner.
- Return a nullable type (System.Nullable<T>) if the target member returns a value type.
- Available as both a member operator (?.) and an index operator (?[…]).

Vipul MalhotraPosted Sep 6, 2015, 5:09 PM
Thanks for sharing
Sibeesh VenuPosted Aug 24, 2015, 9:24 AM
Nice Share :)
Shakti SaxenaPosted Aug 24, 2015, 8:29 AM
Thanks all :)
Guest UserPosted Aug 24, 2015, 8:21 AM
I liked T? example
Ankit BansalPosted Aug 24, 2015, 5:34 AM
nice...
Gowtham KPosted Aug 24, 2015, 3:01 AM
Nice share
Sumit JoshiPosted Aug 24, 2015, 2:36 AM
Thanks for sharing...
Rajeesh MenothPosted Aug 24, 2015, 12:33 AM
Good One
Mohammed IbrahimPosted Aug 23, 2015, 11:25 PM
nice...
Karthikeyan KPosted Aug 23, 2015, 11:18 PM
Good one sir...Thanks for share