开发者

Does a ValueType get boxed when is declared as part of a class?

Considering this class:

public class Foo
{
    public Int32 MyField;
}

I guess the "MyField" member is not on the thread stack because as it could be accessed by several threads, it has to be definitely in the managed heap, but does it means it is boxed and unboxed e开发者_高级运维verytime it is used?

Thanks in advance


No, it is not boxed every time it is used. Boxing only occurs when you are coercing a value type into a reference type - it really has nothing to do with where the actual memory for the value was allocated (or even if any memory was allocated).

In your case, it's how you act on MyField that will determine if it's boxed, not how Foo is treated.

  //No Boxing
  var f = new Foo();
  f.MyField = 5;
  int val = f.MyField;


  //Boxing
  var f = new Foo();
  f.MyFIeld = 5;
  object val = f.MyField;

Note that in the second example val now contains a reference to a boxed int. MyField is still (and will always remain) an unboxed int and can be accessed without unboxing (thanks for pointing out the needed clarification, LukeH)


No, the value type is not boxed.

Boxing only occurs when you use a value type as though it is an object, for example when storing an int in an array of object. That is:

object[] a = new object[10];
int x = 1;
a[0] = x;

In that case, the value type is boxed.

But a value type stored as a field inside a class is not boxed.


No, boxing only occurs when a value type is treated as a System.Object (usually by implicit casting, i.e. passing it as a method parameter)


Value types only get boxed when they're assigned to a reference type variable (e.g. object). If you never assign MyField to anything other than an int or another struct to which it can be cast (e.g. double), it won't ever be boxed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜