Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I assume sender can be null?

Tags:

c#

resharper

Should I assume a sender (of a CLR event handler) or a d (of a dependency event handler) be null and write some code for the case? Or can I simply mark them as [NotNull] and ignore warnings?

I'm using VS2019 + ReShaper to build a C# project. When "Value Analysis Mode" of R# is set to "Pessimistic (an entity is assumed when it doesn't have explicit NotNull attribute)", it warns sender and d can be null.

//// R# warns sender can be null.
private void OnSomethingHappened(object sender, EventArgs e) {
    //// Should I throw an Exception when sender is null?
    //// Or can I simply mark sender as [NotNull]?
}

//// R# warns d can be null.
private static void (DependencyObject d, DependencyPropertyChangedEventArgs e) 
{
    //// Should I throw an Exception when d is null?
    //// Or can I simply mark d as [NotNull]?
}
like image 436
terborac Avatar asked Sep 11 '25 03:09

terborac


1 Answers

Everyone recommend me that I check an object be null. So, IMO, this would be the best practice in case I'd like to utilize sender (or d) in the method.

    private void OnSomethingHappened([CanBeNull]object sender, EventArgs e) {
        if (!(sender is MyClass mc)) throw new ArgumentException();

        mc.DoSomething();        
    }

EDIT: Now I prefer this:

    private void OnSomethingHappened([CanBeNull]object sender, EventArgs e) {
        var mc = sender as MyClass ?? throw new ArgumentException();

        mc.DoSomething();        
    }
like image 66
terborac Avatar answered Sep 13 '25 18:09

terborac