Should I * always * check for null after a safe throw?

Quick question; Is it always necessary to check the zero value after performing a safe throw? I am doing it like this now, but in this situation:

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

I'm just wondering if I'm thinking about something. I check the null value every time out of habit, but in that case, I think I would prefer to crash if a non-Button object was connected to a handler, which should only be for buttons.

EDIT: Alright, thanks guys. I was just curious if there was a corner that I was missing.

+4
source share
6 answers

I agree - perhaps you better roll out the application if a non-Button is connected, as this handler only makes sense for buttons. Moving with a normal application may even be better than an "how" because you will get an InvalidCastException, rather than a NullReferenceException, which makes the problem very obvious.

+2
source

If you want to crash if the button has not been pressed, do:

 var button = (Button)sender; 

Note that it can still be empty if a null object was passed.

+7
source

It will depend on your code contract.

If you know for sure that it is not null, you do not need to check. You can enter confirmation for verification only in debug mode. Usually I check only zero after I do not check with him before, otherwise I trust my contract, and sometimes I use assert.

 var button = sender is Button ? sender as Button : throw new Exception("Not a button"); 

You can try something like this if you want the Exception to be different from the bad. Again, a formal code contract would be better. Check out this library.

+6
source

Yes. If you want to throw an exception, if you call something on this button :)

+2
source

This is only necessary if you want to avoid a possible NullRefernceExcetion .

+2
source

The answer to the question is when you refer to a "safe throw". If it means something, it means that the throw will be successful.

In such cases, it is better to use the type of the throw that throws, and not the one that returns null (without manually checking), because in this way you are more likely to find the cause of the error.

+1
source

All Articles