views:

635

answers:

4

I was going through some code and came across a scenario where my combobox has not been initialized yet. This is in .NET 2.0 and in the following code, this.cbRegion.SelectedValue is null.

int id = (int)this.cbRegion.SelectedValue;

This code threw a null reference exception instead of an invalid cast exception. I was wondering if anyone knew why it would throw a null reference exception instead of a invalid cast?

A: 

It's attempting to read the object before it casts it. Hence you're getting the null exception instead of a cast exception.

Chris Pebble
A: 

The exception is on the Selected Value which is null. It's never even getting to the cast.

BFree
This is not quite correct. It throws while trying to cast or, specifically, to unbox a null reference.
liggett78
+7  A: 

It has to do with Boxing and unboxing. It is trying to pull an int out of the box (unbox), but the object is null, so you get a null reference exception before it ever gets the change to cast.

Brian Genisio
After reading the article it makes sense
Richard R
+2  A: 

If you compile

object o = null;
int a = (int)o;

and look at the MSIL code, you'll see something like

ldnull
...
unbox.any int32

Now the behavior for unbox.any is specified as follows:

InvalidCastException is thrown if obj is not a boxed type.

NullReferenceException is thrown if obj is a null reference.

This is what you see in your code.

liggett78
COOL, I never even thought about decompiling it and checking out the instructions used. thanks
Richard R