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.
I agree – maybe you’re better off having the app crash if a non-Button is hooked up, since this handler only makes sense for Buttons. Going with a normal cast might even be better than an ‘as’ cast, because you’ll end up with an InvalidCastException rather than a NullReferenceException, which make the problem very obvious.