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. Boxing is implicit; unboxing is explicit. You could refer to Boxing and Unboxing (C# Programming Guide) for more details.
-
myClassA.test(myClassA);
myClassA is of type MyClassA, which is an object. The myClassA as an obj of type object in the test method does not belong to boxing. -
MyClassB myClassB = obj as MyClassB;
Convert obj(myClassA) to MyClassB. It's not unboxing.
Here is an example about boxing and UnBoxing.
internal class Program
{
static void Main(string[] args)
{
MyClassA myClassA = new MyClassA();
MyClassB myClassB = new MyClassB();
myClassB.MyProp = 3;
myClassA.test(myClassB.MyProp); // called "Boxing" [myClassB.MyProp is a int type -- convert to --> test (object obj) object type ]
}
}
class MyClassA
{
public void test (object obj)
{
MyClassB myClassB = new MyClassB();
myClassB.MyProp =(int)obj;// called "UnBoxing" [ obj is a object type --convert to -- > myClassB.MyProp is int type ]
}
}
class MyClassB
{
public int MyProp { get; set; }
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.