Sacha K
Sacha K

Reputation: 642

Can EventArgs ever be null?

I have protected override void OnFormClosing(FormClosingEventArgs e) in some of my code and code analysis gives a CA1062 because I don't check if e is null.

Convention is that EventArgs should never be null; that's why we have EventArgs.Empty. Sure, I could be stupid and pass null instead of EventArgs.Empty when raising some event, but here it will be some auto-generated code that will be raising the FormClosing event so I just suppressed the warning.

Are there some corner cases that could cause EventArgs to be null by the framework and not caused by the programmer?

Upvotes: 3

Views: 967

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

Short answer: yes, you can do this:

public void DoSomething()
{
    OnFormClosing(null);
}

But unless you actually do something like this, you can ignore the warning.

Looking at the source code for class Form, we can find this method, which resumes to this:

    /// <devdoc>
    ///    <para>Raises the FormClosing event for this form when Application.Exit is called.
    ///          Returns e.Cancel returned by the event handler.</para>
    /// </devdoc>
    internal bool RaiseFormClosingOnAppExit() {
        FormClosingEventArgs e = new FormClosingEventArgs(CloseReason.ApplicationExitCall, false);
        OnFormClosing(e);
        return e.Cancel;
    }

So no, there is no way e will be null when the event is raised by WinForms.

Upvotes: 6

Related Questions