Why can't a null-reference exception name the object that has a null reference?

前端 未结 5 2173
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 15:48

It seems to me that a lot of my debugging time is spent chasing down null-reference exceptions in complex statements. For instance:

For Each game As IHomeGam         


        
5条回答
  •  北海茫月
    2020-12-17 16:40

    Exceptions are runtime things, variables are compile time things.

    In fact, the variable in your example is an expression. Expressions are not always simple variables. At runtime, the expression will be evaluated and the method will be called on the resulting object. If the value of that expression is null, the runtime will throw a NullReferenceException. Assume the following:

    Dim a as New MyObject
    Dim b as String = MyObject.GetNullValue().ToString()
    

    What error message should the runtime return if the GetNullValue() method returns null?

提交回复
热议问题