Boxing is the process of explicitly converting a value type into a corresponding reference type. Basically, this involves creating a new object on the heap and placing the value there. Reversing the process is just as easy with unboxing, which converts the value in an object reference on the heap into a corresponding value type on the stack. The unboxing process begins by verifying that the recipient value type is equivalent to the boxed type. If the operation is permitted, the value is copied to the stack.
int i = 123; // The following line boxes i. object o = i;
o = 123; i = (int)o; // unboxing------------------------------------------------------------using System; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int Val = 1; Object Obj = Val; //Boxing int i = (int)Obj; //Unboxing MessageBox.Show("The value is : " + i); } } }
No comments:
Post a Comment