Boxing and unboxing 

In C#, boxing means converting a value type variable into a reference type variable. Unboxing is the opposite of boxing. It refers to the conversion of a reference type variable into a value type variable. Boxing and unboxing are detrimental to the performance of the application as they are an overhead to the compiler. As developers, we should try to avoid them as much as possible; however, it's not always possible and there are several instances that we encounter during programming that make us use this concept.

Let's look at the following example to see how boxing and unboxing works:

static private void BoxAndUnBox()
{
int i = 3;
// Boxing conversion from value to reference type
object obj = i;
// Unboxing conversion from reference type to value type
i = (int)obj;
}

In the code implementation, we can see the following:

  • We have declared a variable, i, of the int type and have assigned it a value of 3. Now we know that, being int, this is a value type reference. 
  • Next, we declare an obj variable of the object type and have assigned it the value in i. We know that object is a reference type variable. Therefore, internally, the CLR will undergo boxing and convert the value into the i variable into a reference type variable.
  • Next, in the third statement, we are doing the reverse. We are trying to assign the value in a reference type variable, that is, obj, to a value type variable, i. At this stage, the CLR will do the unboxing of the value. 

Please note that, while doing boxing, we do not need to explicitly cast the value type to a reference type. However, when we are doing the unboxing, we need to explicitly specify the type into which we are converting the variable. This approach of explicitly specifying the type into which we are converting a variable is known as casting. To do casting, we can use the following syntax:

i = (int)obj;

What it basically means is that there are possibilities that this conversion can lead to an exception of the InvalidCastException type. For example, in the preceding example, we know that the value in obj is 10. However, if it were to acquire a value that cannot be cast to an int value, for example, string, the compiler will give us a runtime error. 

Now, in the next section, we will look at the different techniques C# provides us with for converting between data types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.130.24