Use cases for boxing a value type in C#?

后端 未结 9 1147
既然无缘
既然无缘 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-06 00:11

    Boxing generally happens automatically in .NET when they have to; often when you pass a value type to something that expects a reference type. A common example is string.Format(). When you pass primitive value types to this method, they are boxed as part of the call. So:

    int x = 10;
    string s = string.Format( "The value of x is {0}", x ); // x is boxed here
    

    This illustrates a simple scenario where a value type (x) is automatically boxed to be passed to a method that expects an object. Generally, you want to avoid boxing value types when possible ... but in some cases it's very useful.

    On an interesting aside, when you use generics in .NET, value types are not boxed when used as parameters or members of the type. Which makes generics more efficient than older C# code (such as ArrayList) that treat everything as {object} to be type agnostic. This adds one more reason to use generic collections, like List or Dictionary over ArrayList or Hashtable.

提交回复
热议问题