Question

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 everytime it is used?

Thanks in advance

Was it helpful?

Solution

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)

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top