Java vs. C#

Boxing vs. Unboxing


Java 5
 
You may not be allowed to convert any primitives
to reference types directly with assignment 
operator using jdk version below 1.5. 
int i = 123;
Object box = i; //OK for jdk 1.5

Integer ii = new Integer(i);
Object box = ii;


Integer ii = new Integer(123); Object box = ii; int i = ((Integer)box).intValue(); System.out.println(i);//123
class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } Point p = new Point(10, 10); Object box = p; p.x = 20; System.out.print(((Point)box).x);//20 //Point is a reference type
int i = 5; Stack stack = new Stack (); stack.push (new Integer(i)); //wrapper int j = (stack.pop()).intValue();

C#
 
You may convert any value type to a corresponding 
reference type, and to convert the resultant 'boxed' 
type back again.

int i = 123;
object box = i;
if (box is int) {
   System.Console.Write("Box contains an int");
}

unboxing object box = 123; int i = (int)box; System.Console.Write(i);//123
struct Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } Point p = new Point(10, 10); object box = p; p.x = 20; System.Console.Write(((Point)box).x);//10 //Point is a value type
int i = 5; Stack stack = new Stack (); stack.Push (i); // box the int int j = (int) stack.Pop(); // unbox the int