Boxing and Unboxing

C#'s type system is unified such that a value of any type can be treated as an object. Every type in C# directly or indirectly derives from the object class type, and object is the ultimate base class of all types. Values of reference types are treated as objects simply by viewing the values as type object. Values of value types are treated as objects by performing boxing and unboxing operations. In the following example, an int value is converted to object and back again to int.


using System;
class Test
{
static void Main() {
int i = 123;
object o = i; // Boxing
int j = (int)o; // Unboxing
}
}



Reference: www.dotnetmaterial9.blogspot.com


Comments

Author: Sanjay20 Jul 2010 Member Level: Silver   Points : 2

namespace boxing_and_unboxing
{
class Number
{
static void Main(string[] args)
{
int num = 8;
int result;
result = squre(num);
Console.WriteLine("Squre of {0}={1}",num,result);
}

static int squre(object inum)
{
return (int)inum * (int)inum;
}
}
}

Author: Pal (Parthiv) Patel21 Jul 2010 Member Level: Gold   Points : 0

Thanks dude



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: