Use cases for boxing a value type in C#?

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

    One of the situations when this happens is for example if you have method that expect parameter of type object and you are passing in one of the primitive types, int for example. Or if you define parameter as 'ref' of type int.

    0 讨论(0)
  • 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<T> or Dictionary<T,K> over ArrayList or Hashtable.

    0 讨论(0)
  • 2021-02-06 00:11

    One example would when a method takes an object parameter and a value type must be passed in.

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