Search code examples
c#.neteventsc#-7.0null-conditional-operator

Is there any Null-Conditional Operator like for Events.. Button?.Click +=(ss,ee)


Why there's no Null-Conditional Operator for events ?

For example i have following code which raise event if object is not null :

Button TargetButton =  null;

    if(IsRunning)
    {
       TargetButton = new ....
    }

TargetButton?.Click +=(ss,ee)=>{...}

// Compile-time error 
// The event 'EditorButton.Click' can only appear on the left hand side of += or -= 

briefly :

is there alternative ? than using usual if(TargetButton != null ) ... raise event

Why there's no null-conditional operator for event. and it accept null ? http://prntscr.com/pv1inc


Solution

  • The problem is not related to events.

    The null-conditional operator is to stop an evaluation if a reference is null.

    It is not applicable in the left or right part of an assignment.

    If you have:

    public class Test
    {
      public int Value;
      public void Method() { }
    }
    

    You can't write:

    Test v;
    
    v?.Value = 10;
    
    int a = v?.Value;
    

    Because if v is null, v.Value is not evaluated.

    • So what to do with = 10 ?

    • Or what to do with a ?

    Thus it is the same when adding or removing an event handler to an event variable that is null when empty.

    C# event is null

    Hence the compiler error to disallow such writings.

    It is why you can't write:

    TargetButton?.Click +=(ss,ee)=>{...}
    

    Because what to to with (ss,ee)=>{...} if TargetButton is null?

    You can say that you want the compiler ignores that.

    But the compiler disallows doing such unclean thing.

    What we can write is:

    v?.Test();
    

    Here is v is null the method is not called and all is fine because there is nothing right or left that the compiler does not know what to do with.

    int a = v?.Value ?? 0;
    

    Here if v is null 0 is used.

    Null-conditional operators ?. and ?[]

    Null-coalescing operators ?? and ??=