Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

C# Boxing and unboxing



C# Type System contains three Types; they are Value Types, Reference Types and Pointer Types. C# allows us to convert a Value Type to a Reference Type, and back again to Value Types. The operation of Converting a Value Type to a Reference Type is called Boxing, and the reverse process is called Unboxing.

Boxing

int Val = 1;
Object Obj = Val; //Boxing

The first line we created a Value Type Val and assigned a value to Val. The second line, we created an instance of Object Obj and assigned the value of Val to Obj. From the above operation (Object Obj = i ), we saw converting a value of a Value Type into a value of a corresponding Reference Type. These types of operation are called Boxing.

UnBoxing

int Val = 1;
Object Obj = Val; //Boxing
int i = (int)Obj; //Unboxing

The first two line shows how to Box a Value Type. The next line (int i = (int) Obj) shows extracts the Value Type from the Object . That is converting the value of a Reference Type into a value of a Value Type. This operation is called UnBoxing.
Boxing and UnBoxing are computationally expensive processes. When a value type is boxed, an entirely new object must be allocated and constructed, also the cast required for UnBoxing is also costly computationally.

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);
        }
    }
}

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More