Why does casting a null to a primitive(ie: int) in .net 2.0 throw a null ref exception and not a invalid cast exception?

前端 未结 4 889
生来不讨喜
生来不讨喜 2021-01-20 16:57

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.Select

相关标签:
4条回答
  • 2021-01-20 17:08

    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.

    0 讨论(0)
  • 2021-01-20 17:21

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

    0 讨论(0)
  • 2021-01-20 17:24

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

    0 讨论(0)
  • 2021-01-20 17:33

    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.

    0 讨论(0)
提交回复
热议问题