Why does casting a null to a primitive (i.e., Int) in .net 2.0 result in a null ref exception and not an invalid cast exception?

I was looking at some code and came across a script in which my combobox had not yet been initialized. This is in .NET 2.0 and in the following code this.cbRegion.SelectedValue is null.

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

In this code, instead of throwing an invalid exception, a null reference exception is selected. I was wondering if anyone knows why he chose the exclusion of the link instead of invalid casting?

+3
source share
4 answers

This is due to boxing and unboxing. It tries to pull an int out of the box (unbox), but the object is null, so you get an exception for the reference link before it ever gets the change for translation.

+9
source

If you compile

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

and look at the MSIL code, you will see something like

 ldnull ... unbox.any int32 

Now the behavior for unbox.any is as follows:

An InvalidCastException is thrown if obj is not a boxed type.

Throw NullReferenceException if obj is a null reference.

This is what you see in your code.

+7
source

He is trying to read the object before he produces it. Therefore, you get a null exception instead of an exception exception.

+1
source

An exception is the selected value, which is null. He doesn't even get into casting.

0
source

All Articles