Ed Swangren
Ed Swangren

Reputation: 124642

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

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.

Upvotes: 4

Views: 864

Answers (6)

Daniel Earwicker
Daniel Earwicker

Reputation: 116674

The answer is in the question when you refer to a "safe cast". If that means anything, it means that the cast is going to succeed.

In such cases it is better to use the kind of cast that throws rather than the kind that returns null (without checking manually), because that way you will find the cause of a bug sooner.

Upvotes: 2

Andy White
Andy White

Reputation: 88355

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.

Upvotes: 2

Edwin Jarvis
Edwin Jarvis

Reputation: 6130

That will depend on your code contract.

If you know for sure that is not null you don't need to check. You can introduce an assert to check only on debugging mode. I normally only check for null after an as if I don't make a check with is 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 an Exception different from bad cast. Again, a formal code contract would be better. Check out this library.

Upvotes: 6

Andrew Hare
Andrew Hare

Reputation: 351516

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

Upvotes: 2

MichaelGG
MichaelGG

Reputation: 10006

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.

Upvotes: 7

Leonidas
Leonidas

Reputation: 2438

Yes. Except you want to cause an exception if you call something at this button :)

Upvotes: 2

Related Questions