Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible Null Reference Exception using "as" operator

In the following code:

MyObject objInstance;

private void someEventHandler(object sender, EventArgs e)
{
    if (sender == objInstance && (sender as MyObject).SomeBoolProperty)
        // Do Something
}

Resharper is warning that sender as MyObject may be a possible NullReferenceException. Is that possible given this code? I'm assuming that if sender == objInstance that (sender as MyObject) won't return null, but this wouldn't be the first time a Resharper message has informed me of a C# behavior/feature I was unaware of.

like image 213
Harrison Paine Avatar asked Feb 26 '26 07:02

Harrison Paine


1 Answers

When you use as, null is returned if the object couldn't be converted (in this case, to MyObject). Therefore, your line (sender as MyObject) has the potential to be null.

like image 175
keyboardP Avatar answered Feb 28 '26 21:02

keyboardP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!