Mega Code Archive
0154 Boxing and unboxing
Boxing is the process of casting value type to reference type.
Unboxing casts the reference type to value type.
The following code is boxing the i to object.
using System;
class Program
{
static void Main(string[] args)
{
int i = 0;
object obj = i;
Console.WriteLine(obj);
}
}
The output:
0
The unbox requires an explicit cast.
using System;
class Program
{
static void Main(string[] args)
{
int i = 0;
object obj = i;
int j = (int)obj;
Console.WriteLine(obj);
Console.WriteLine(j);
}
}
The output:
0
0