Boxing is when a value type is assigned to an object type. Is it the same when a reference type is assigned to an object?
When a type (which isn't object) is assigned, what happens? Is that boxing too?
int num=5;
object obj = num; //boxing
//////////////////////
MyClass my = new MyClass();
object obj = my; //what is name this convert (whethere is boxing?)
Boxing is creating an object reference, on the stack, that references a value of the type say for e.g. int, on the heap. But when a reference type (witch isn't object)assigned to object, it is not boxing.
Close. "Boxing" happens when a value of value type is converted to a reference type.
No. Boxing happens when a value of value type is converted to a reference type. Converting a value of reference type to object is not a boxing conversion, it is a reference conversion.
A value of reference type is a reference. When a reference is assigned to a variable of type object, a copy of the reference is made in the storage location associated with the variable.
No. Boxing happens when a value of value type is converted to a reference type. Converting a value of reference type to object is not a boxing conversion, it is a reference conversion.
Compiling the provided code into a working executable and disassembling it reveals an explicit box instruction for the first assignment (
obj
) that is not present for the second (obj2
):Source
CIL
Eric's answer corresponds to the CLI (Common Language Infrastructure) standard ECMA-335, partition I (Architecture), chapter 5 (Terms and definitions), which defines boxing as: "The conversion of a value having some value type, to a newly allocated instance of the reference type System.Object.", and unboxing as: "The conversion of a value having type System.Object, whose run-time type is a value type, to a value type instance."
The box and unbox instructions of the CIL (Common Intermediate Language) behave like this, and this is also the meaning usually implied when speaking of boxing/unboxing in the context of C# or VB.NET.
However, the terms boxing and unboxing are sometimes used in a wider/pragmatic sense. For instance, the F# box and unbox operators can do conversions of value types and reference types to and from System.Object:
I assume you mean something like
This works because
System.String
, like all other classes, derives fromSystem.Object
: