Why does .ToString() on a null string cause a null error, when .ToString() works fine on a nullable int with null value?

前端 未结 8 1297
耶瑟儿~
耶瑟儿~ 2020-11-30 12:19

selectedItem has two fields:

  • int? _cost
  • string _serialNumber

In this example, _cost

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 12:49

    what i think the reason is, when the compiler encounters a primitive data type it wraps it, to its corresponding object. The toString() method call is just an indirect call(wrapping and then calling the method) here and the exception is handled there. While in the case of String, we are directly calling the method. When pointing to a null, the method throws the exception.

提交回复
热议问题