Web Design that taps into the haromny and vision of your dreams.

Boxing and Unboxing Value Types in C#

Object Orientation concept of Boxing and Unboxing

Written By on in C#

400 words, estimated reading time 2 minutes.

Boxing and Unboxing are essential concepts in C#. They form a link between a reference type and a value type.

Advanced C# Programming Series
  1. C# Advanced Data Types
  2. Using C# Properties and Indexers
  3. C# Event Handling and Delegates
  4. Method Overloading and Overriding in C#
  5. C# Class Abstraction and Encapsulation
  6. C# Aggregation and Advanced Scope Techniques
  7. Polymorphism in C#
  8. Boxing and Unboxing Value Types in C#
  9. C# Operator Overloading
  10. Creating Multi-Threading Applications with C#
  11. Unsafe Code Execution in Microsoft .Net

Boxing and Unboxing are made possible because of the .Net framework common type system (CTS) which means that all types, reference and value, derived from the type object. It is possible to call methods on a value, such as 100.

Try it in the editor, type the numeral 100 followed by a full stop to invoke IntelliSense. Notice that there are various methods including Equals, GetHashCode, GetType and ToString. These are all inherited from the base CTS object.

string numberAsString = 100.ToString();

Boxing is a process by which any value type (or reference type) can be treated as a reference type object and worked on before being unboxed back to its original value type.

int myInteger = 12345;
 
// myInteger is boxed
object Box = myInteger;
 
// myInteger is unboxed
int anotherInteger = (int)Box;

Why would you want to do this? Well, suppose you need an array of objects that do not have the same type and need to iterate through them.

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        int a = 3;
        decimal b = 4.35M;
        string c = "Hello";
 
        object[] myList = new object[3];
 
        // Box up the value and reference types together
        myList[0] = a;
        myList[1] = b;
        myList[2] = c;
 
        // Unbox the types
        foreach (object unboxed in myList)
        {
          // Output the type of the object
          Console.WriteLine(unboxed.GetType());
 
          if (unboxed.GetType() == typeof(int))
          {
              // The object was an Int
              int unboxedInteger = (int)unboxed;
          }
          else if (unboxed.GetType() == typeof(string))
          {
              // The object was a string
              string unboxedString = (string)unboxed;
          }
          else if (unboxed.GetType() == typeof(decimal))
          {
              // The object was a decimal
              decimal unboxedDecimal = (decimal)unboxed;
          }
        }
    }
}

This can be especially useful when dealing with a collection of controls, such as a PlaceHolder in ASP.Net. The placeholder.Controls collection maintains a list of all the controls derived from the Control class. These can be buttons, text boxes, images, hyperlinks and so on.

Let's say we wanted to clear the text of all text boxes in PlaceHolder1. We could do that with a loop like the one shown below using the is keyword.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class SiteMaster : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        foreach (Control ctrl in PlaceHolder1.Controls)
        {
            if (ctrl is TextBox)
            {
                TextBox tb = (TextBox)ctrl;
                tb.Text = string.Empty;
            }
        }
    }
}

Last updated on: Friday 23rd June 2017

 

Comments
Benjamin

Benjamin

Very nice explanation,easy to understand.
Thanks Tim Trott

Reply to Benjamin
Naeem

Naeem

Very nice example... totally clear

Reply to Naeem
Arjunan

Arjunan

Really Nice example for Boxing and Unboxing..Clear Explanation...Keep it up..

Reply to Arjunan
tamir

tamir

nice one this is real advance!
keep on the great work!

Reply to tamir

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me