Search code examples
c#.netc#-8.0nullable-reference-types

adding event handler on event of nullable object


I'm creating some test WinForms project and trying to create items for my ContextMenuStrip at runtime. But, I can't add an EventHandler to an event ItemClicked using null-conditional operator (?.):enter image description here

Why is that happening?

However if I remove null-conditional operator, it works but gives a warning: enter image description here


Solution

  • Do this

    if (this.ContextMenuStrip != null)
        this.ContextMenuStrip.ItemClicked += Strip_ItemClicked;
    

    You're having nullable compiler complaint. This is one of those sticky situations. If you had decision condition, you could get away with

    if (this.ContextMenuStrip?.Enabled ?? false)
    

    But if you know that even though your component is declared as nullable but due to logic it can't be null at this particular place in code, you can override nullable check with ! (null-forgiving) operator

    this.ContextMenuStrip!.ItemClicked += Strip_ItemClicked;