Guidelines for events since non-nullable references

You should make the event nullable, because it is indeed nullable. It may look a bit strange but that’s the correct way of expressing your intent.

It has always been necessary to check whether an event is null before raising it within the class. In this case nullable reference checking will warn you if you try to invoke it without checking for null.

    public class Publisher
    {
        public event EventHandler? IdleTimeoutReached;

        protected virtual void RaiseIdleTimeoutEvent()
        {
            // `IdleTimeoutReached` will be null if no subscribers; compiler gives warning about possible null reference
            IdleTimeoutReached.Invoke(this, EventArgs.Empty);

            // No compiler warning
            IdleTimeoutReached?.Invoke(this, EventArgs.Empty);
        }
    }

The nullable annotation really only adds value for the class invoking the event. It won’t affect callers at all because the += / -= syntax takes care of correctly assigning/removing those delegates.

So you should use:

public event EventHandler? IdleTimeoutReached;

For events with EventArgs, use:

public event EventHandler<IdleTimeoutEventArgs>? IdleTimeoutReached;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)