When working with C# 8 and the new non-nullable references, I realized that events are treated like fields. This means that they will cause a warning 90% of the time since they won't be initialized until someone subscribes to it.
Consider the following event:
public event EventHandler IdleTimeoutReached;
You get the following warning on the line of the constructor declaration.
CS8618 C# Non-nullable event is uninitialized. Consider declaring the event as nullable.
If you make it nullable, the warning disappears of course. However, this looks very weird to me.
public event EventHandler? IdleTimeoutReached;
An alternative would be assigning it a no-op, but this seems even worse.
public event EventHandler IdleTimeoutReached = new EventHandler((o, e) => { });
What's the correct way to handle this situation and get rid of the warning without just disabling it? Are there any official guidelines for this?
EventHandler?weird given thatEventHandleris a delegate (reference type) that may acutally be uninitialized?null, hence patterns likeIdleTimeoutReached?.Invoke(). It would make no sense for the compiler to lie to you and say "no, it's fine" only to then have invoking the event actually fail because it'snull. The fact that callers don't have to deal with this (because the+=syntax takes care of it, and they're not allowed to get the value raw) is what's causing the confusion, but even to them the value really isnull, and the delegate combination operator just transparently deals with that for them.public event EventHandler SomeEvent = delegate {}. This initializer syntax works for any event type.