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

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

selectedItem has two fields:

  • int? _cost
  • string _serialNumber

In this example, _cost

相关标签:
8条回答
  • 2020-11-30 12:58

    A string is a reference type, but a nullable int is a value type. Here is a Good discussion of the differences http://www.albahari.com/valuevsreftypes.aspx.

    0 讨论(0)
  • 2020-11-30 12:59
    TextBox2.Text = selectedItem.SerialNumber.ToString(); //error
    

    yiels error because it's calling function ToString() which is member of System.String. This function returns this instance of System.String; no actual conversion is performed. Also, String is a reference type. A reference type contains a pointer to another memory location that holds the data.

    TextBox1.Text = selectedItem.Cost.ToString(); //no error
    

    yields no error because it's calling to function ToString() which is a member of System.Integer. This function converts the numeric value of this instance to its equivalent string representation. Also, Integer is a value type. A data type is a value type if it holds the data within its own memory allocation.

    The same function name ToString() but performs different task.

    String.ToString Method

    Int32.ToString Method

    Value types and reference types

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