6

Before we had Nullable Reference Types (NRT) in C#, events and trigger methods would be declared like this:

public event EventHandler MyEvent;

private void TriggerEvent()
{
    this.MyEvent?.Invoke(this, EventArgs.Empty);
}

Now, with NRTs enabled, should the event type be declared as EventHandler or EventHandler?:

public event EventHandler MyEvent;
// or
public event EventHandler? MyEvent;

private void TriggerEvent()
{
    this.MyEvent?.Invoke(this, EventArgs.Empty);
}

I'd say EventHandler? but all the C# documentation I could find (still) says EventHandler (without ?).

Update: Editing this question because someone (?) flagged this as duplicate of this question - which is clearly not a duplicate. I know what ? means. That's not the question here.

Sebastian Krysmanski
  • 8,114
  • 10
  • 49
  • 91
  • 2
    I deleted my previous comment as it contained false information, turns out, Microsoft aimed to be done with null-annotating their core libraries once .NET 5 released and their progress was tracked in [this](https://github.com/dotnet/runtime/issues/2339) GitHub issue. So it seems like only the documentation is lacking, but yes, you should definitely use `EventHandler?` – MindSwipe Jun 21 '21 at 09:55
  • Do you get a compiler warning or what is wrong with old version? You can set [#nullable disable](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references) and use old syntax. – Sinatr Jun 21 '21 at 09:58

1 Answers1

7

You are correct; it should indeed be EventHandler? since unsubscribed events (the default) are backed by a null delegate instance (at least when using field-like-events, as per here). The documentation simply doesn't always accommodate nullable reference type signatures.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900