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

一笑奈何 提交于 2019-12-03 14:22:24

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.

empi

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.

Tigran

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!