Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I *always* have to check for null after a safe cast?

Tags:

c#

Quick question; do I always need to check for a null value after performing a safe cast? I do it this way now, but in a situation like this:

void button1_Click(object sender, EventArgs e)
{
    Button = sender as Button;
    if (button != null)  // <-- necessary?
    {
        // do stuff with 'button'
    }
}

I am just wondering if I am not thinking of something. I check for null every time out of habit, but in a case like this I think that I would prefer a crash if a non-Button object was hooked up to a handler that should only be for buttons.

EDIT: OK, thanks guys. I was just curious if there was an angle that I was missing.

like image 515
Ed S. Avatar asked Nov 30 '22 12:11

Ed S.


1 Answers

If you want to crash if a non-Button was passed in, do:

var button = (Button)sender;

Note that it could still be null, if a null object was passed in.

like image 148
MichaelGG Avatar answered Dec 16 '22 00:12

MichaelGG