VS proposed to "simplify"

... EventHandler<MyEventArgs> args = MyHandler if (args != null) { args(this, e); } ... 

On

 ... MyHandler?.Invoke(this, e) ... 

What does it mean? Where to dig?

    3 answers 3

    In C # 6, a so-called null propagation operator appeared. It allows you to simplify quite tedious checks on null, and means that if the expression on its left side is null, then it will return null, and if it has some other value, the field / property value from the right side will be returned, or The method from the right side is executed. Agree to write

     data = some?.GetData(); 

    clearly more convenient than

     if(some != null) data = some.GetData(); 
    • 2
      moreover - this design is thread - safe - Andrew NOP

    This design

     MyHandler?.Invoke(this, e); 

    logically equivalent to the following

     if ( MyHandler != null ) MyHandler.Invoke(this, e); 

    The same construction was introduced for the index operator. for example

     int[] a = null; int? x = a?[0]; a = new int[1] { 10 }; int? b = a?[0]; 

    This tool appeared in the new version of C # 6.0

    • The expression MyHandler should be evaluated only once, and for you it is evaluated twice when the condition MyHandler != null true. - PetSerAl
    • @PetSerAl That's why they introduced such a construction. :) - Vlad from Moscow 1:08 pm

    The keyword null is a literal representing a null reference that does not reference any object. null is the default value of reference type variables.

    For the keyword null , special operators are defined:

    • int? a;
      We allow the use of null for the value type . Instead of int you can specify any type of value.
    • obj?.SomeMethod();
      We check the obj object for null and, if the object is not null , we refer to the type member.
      Also besides ?. can I contact the indexer ?[] .
    • int y = x ?? -1;
      Check if x != null , take its value, otherwise do we execute the construction to the right of ?? , in this case, set y = -1 .

    You can also combine with each other:

     int? length = customers?.Length ?? -1; // если customers != null, вернуть customers.Length, иначе вернуть -1