Does unboxing occur when a class's value-type member is referenced?

1.5k views Asked by At

I read What is boxing and unboxing and what are the trade offs? but can't understand one thing. Suppose I have a class:

class MyClass
{
    public int Value { get; set; }
}

And I want to get value within my method:

void MyFunc(MyClass cls)
{
    int i = cls.Value;
}

As a class placed in heap, I guess that Value placed in a heap too? And therefore operation

int i = cls.Value;

is unboxing? Or it's not unboxing?

4

There are 4 answers

0
Tigran On

It's neither unboxing nor boxing. Considering you assign to int without cast and, I hope, this code compiles, that means that cls.Value is a Integer(int) type. So assign int to int. What happens here is a value copy.

0
empi On

Boxing or unboxing doesn't have anything to do with storing values on heap or stack. You should read the article "Boxing and Unboxing" from the C# Programming Guide. In your example none of these two occurs because you're assigning int to int.

5
Olivier Jacot-Descombes On
int i = 5;
object o = i;   // boxing of int i
int i = (int)o; // unboxing of object o

Note that we do not assign i to a field or property of an object, but to the object itself. It is comparable to the nature of light. Light can be perceived of being made of particles (photons) or being a wave. An int can be an int object (a reference type) or an int value type. You can however not define an int to be a reference type directly; you must convert it to an object, e.g. by assigning it to a variable, parameter or property of type object or casting it to object to make it a reference type.

24
Eric Lippert On

Stop thinking about stack and heap; that's completely the wrong way to think about it. It is emphatically not the case that "boxed" means "on the heap", and therefore anything "on the heap" must be "boxed".

Stack and heap are irrelevant. Rather, think about references and values. A value of value type is boxed when it must be treated as a reference to an object. If you need to have a reference to a value of a value type, you make a box, put the value in the box, and make a reference to the box. And there, now you have a reference to a value of value type.

Do not confuse that with making a reference to a variable of value type; that is completely different. A variable and a value are two very different things; to make a reference to a variable you use the "ref" keyword.