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?)
Objects are an example of a reference type. In the above example, both variables a and b will point to the same student object in memory.
Variables of reference types store references to their data (objects), while variables of value types directly contain their data. With reference types, two variables can reference the same object; therefore, operations on one variable can affect the object referenced by the other variable.
Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the common language runtime (CLR) boxes a value type, it wraps the value inside a System. Object instance and stores it on the managed heap. Unboxing extracts the value type from the object.
Implicit conversion of a value type (int, char, etc.) to a reference type (object), is known as Boxing. In the boxing process, a value type is being allocated on the heap rather than the stack. A boxing conversion is intended for creating a copy of the value being boxed.
Boxing is when a value type is assigned to an object type.
Close. "Boxing" happens when a value of value type is converted to a reference type.
Is it the same when a value of reference type is assigned to a variable of type object?
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.
When a value of reference type (which isn't object) is assigned to a variable of type object, what happens?
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.
Is that boxing too?
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.
I assume you mean something like
string s = "hello";
object x = s; // no boxing, just implict conversion to base-type.
This works because System.String
, like all other classes, derives from System.Object
:
public sealed class String : Object { ... }
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