Understand Boxing And Unboxing In C#

  1. using System;  
  2. class BoxUboxTest {  
  3.     static void Main(string[] args) {  
  4.         int m = 10;  
  5.         object a = m; // boxing  
  6.         try {  
  7.             Console.WriteLine("Value of m is:" + a);  
  8.             // unbox  
  9.             object n = 20;  
  10.             int b = (int) n;  
  11.             Console.WriteLine("Value of n is:" + b);  
  12.             System.Console.WriteLine("Unboxing OK.");  
  13.             Console.ReadKey();  
  14.         } catch (System.InvalidCastException e) {  
  15.             System.Console.WriteLine("Error: Incorrect unboxing." + e.Message);  
  16.         }  
  17.     }