Search code examples
c#.netmemory-managementboxingunboxing

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

Thanks in advance


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)