Use cases for boxing a value type in C#?

后端 未结 9 1143
既然无缘
既然无缘 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:52

    There is almost never a good reason to deliberately box a value type. Almost always, the reason to box a value type is to store it in some collection that is not type aware. The old ArrayList, for example, is a collection of objects, which are reference types. The only way to collect, say, integers, is to box them as objects and pass them to ArrayList.

    Nowadays, we have generic collections, so this is less of an issue.

提交回复
热议问题