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?
Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object. In the following example, the integer variable i is boxed and assigned to object o .
With Generics you avoid doing boxing/unboxing since you are dealing with the parameter type T , which is a natural parameter that the compiler will replace it with the concrete type at compilation time without doing the boxing operation at runtime.
The basic difference between Boxing and Unboxing is that Boxing is the conversion of the value type to an object type whereas, on other hands, the term Unboxing refers to the conversion of the object type to the value type.
Unboxing In C# The process of converting a Reference Type variable into a Value Type variable is known as Unboxing. It is an explicit conversion process. Example : int num = 23; // value type is int and assigned value 23 Object Obj = num; // Boxing int i = (int)Obj; // Unboxing.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With