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, 1:09 PM EDT
Thanks for sharing
Sibeesh VenuTOP 100Posted Aug 24, 2015, 5:24 AM EDT
Nice Share :)
Shakti SaxenaPosted Aug 24, 2015, 4:29 AM EDT
Thanks all :)
Guest UserPosted Aug 24, 2015, 4:21 AM EDT
I liked T? example
Ankit BansalPosted Aug 24, 2015, 1:34 AM EDT
nice...
Gowtham KTOP 100Posted Aug 23, 2015, 11:01 PM EDT
Nice share
Sumit JoshiPosted Aug 23, 2015, 10:36 PM EDT
Thanks for sharing...
Rajeesh MenothPosted Aug 23, 2015, 8:33 PM EDT
Good One
Mohammed IbrahimPosted Aug 23, 2015, 7:25 PM EDT
nice...
Karthikeyan KPosted Aug 23, 2015, 7:18 PM EDT
Good one sir...Thanks for share