Search code examples
c#.netvalue-typeboxing

Is value type boxing when it is a field of reference type?


There is code:

struct A
{
   int b;
}

class B
{
  A a;
  int b;
}

Questions are:

  1. Is a in B boxed or not?
  2. Is a in B located in stack or in heap?
  3. Is b in A boxed or not?
  4. Is b in A stack or in heap?
  5. Is b in B boxed or not?
  6. Is b in B stack or in heap?

I really don't understand It :(


Solution

  • 1) No, there's no boxing here.

    2) a will be on the heap, although that's an implementation detail

    3) No, b in A isn't boxed

    4) b in A will live wherever the containing A will live (so with a local variable of type A it'll usually be on the stack; with an instance variable of a class like B or any static variable, it'll be on the heap); again, this is an implementation detail

    5) b in B isn't boxed either

    6) b in B will be on the heap - again, an implementation detail

    There's no boxing going on here as you haven't shown anything trying to use a value type value as a reference type value (e.g. object or an interface).

    Again, the whole stack/heap distinction is an implementation detail. You should read Eric Lippert's blog posts on the topic.