BOXING AND UNBOXING

In c# everything is object. The object is a reference type.

What is boxing and unboxing?

The boxing is a concept to convert value type to reference type. The unboxing is a concept to convert reference type to value type.

In basic the value types stored in stack and reference type stored in hash table.

Example of boxing:

//boxing
            int i = 12;
            object j = i;
            if (j is int)
            {
                Console.WriteLine("j contains an int");
                Console.ReadLine();
            }

Here we converting I value type to j reference type.

Example of Unboxing:

Unboxing is reverse to boxing.

Let consider two froms from1 and form2.In form1 you having two button control's that having the text's of “hello” and “hai”.now you have to show your button text when you clicking button.Here the button event should be same for two button's.

Like

             private void button1_Click(object sender, EventArgs e)
            {
                        Button b = (Button)sender;//unboxing
                        Form2 frm = new Form2();
                        frm.b = b.Text; //frm.b is a public variable of form2
                        frm.Show();
  }

Here you used unboxing to optimize your code.

Then you can use the below code to show the clicked button text.

                        private void Form2_Load(object sender, EventArgs e)
                        {

                                    label1.Text = b;
            }

Ebook Download
View all
Learn
View all