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]?
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With