C# events with nullable reference types enabled - how to declare?

Viewed 526

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.

1 Answers

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.

Related