Use cases for boxing a value type in C#?

后端 未结 9 1146
既然无缘
既然无缘 2021-02-05 23:36

There are cases when an instance of a value type needs to be treated as an instance of a reference type. For situations like this, a value

9条回答
  •  梦谈多话
    2021-02-05 23:49

    The code

    int x = 42;
    Console.Writeline("The value of x is {0}", x );
    

    actually boxes and unboxes because Writeline does an int cast inside. To avoid this you could do

    int x = 42;
    Console.Writeline("The value of x is {0}", x.ToString());
    

    Beware of subtle bugs!

    You can declare your own value types by declaring your own type as struct. Imagine you declare a struct with lots of properties and then put some instances inside an ArrayList. This boxes them of course. Now reference one through the [] operator, casting it to the type and set a property. You just set a property on a copy. The one in the ArrayList is still unmodified.

    For this reason, value types must always be immutable, i.e. make all member variables readonly so that they can only be set in the constructor and do not have any mutable types as members.

提交回复
热议问题