Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :(

like image 696
Vasya Avatar asked Dec 21 '22 08:12

Vasya


2 Answers

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.

like image 135
Jon Skeet Avatar answered Dec 24 '22 01:12

Jon Skeet


Using Google I found this:

Boxing and unboxing is a essential concept in C#’s type system. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object. Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object. Converting a value type to reference type is called Boxing. Unboxing is an explicit operation.

Boxing is converting a value type to reference and that's not in you code. So answer to your "b-boxed" questions is "No".

like image 26
Karel Frajták Avatar answered Dec 24 '22 01:12

Karel Frajták