Boxing and Unboxing in C#

In this post,We will learn about Boxing and Unboxing in C# with an example.

Boxing and Unboxing in C#

Boxing & Unboxing in C#

Description:

In my previous posts I have explained various topics like Dynamic Type In C#, Named Arguments In C#, Basics Of Pointers In C#, Get site visitor count in asp.net, Convert generic list to datatable in Asp.Net C#.Net, Abstract Class in C# with Example.

Now in this post, I will explain about Boxing and Unboxing in C# with appropriate example. Many time knowingly or unknowingly we use these concepts and it can have disastrous performance issues in application. So in this article we will see what is boxing and unboxing and how does it cause performance problem and how to use them carefully to avoid these issues.




Boxing

So let us start with boxing and below are some points and definitions around it.

  • It is a process of converting value type to the referenced type.
  • Value type variables are stored in Stack Memory

Now create Console Application in Visual Studio and write below lines of code in it.

static void Main(string[] args)
{
   int count = 10; // Step 1 Declare count of integer datatype.
   object obj; // Step 2 :- Declaration of Object obj.
   obj = count; // ß Step 3 :- Boxing happens here .Assigning value of count  to object obj.
}

Unboxing

  • Unboxing is a process of converting reference type to the value type.
  • Referenced Type variables are stored in Heap Memory.
    static void Main(string[] args)
    {
       int count = 10; // Declaration and Initialisation of Variable count of integer datatype.
       object obj; // Declaration of Object obj.
       obj = count; // Boxing
       int j = (int)obj; // Unboxing
    }

     

Summary

I hope you got an idea about Boxing and Unboxing in C#.
I would like to have feedback from blog my  readers.
Your valuable feedback, question, or comments about this article are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website