"Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap.Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit."During the process of unboxing two types of exception can be appeared:
- NullReferenceException ( if you try to unbox null object)
- InvalidCastException ( if you try to unbox to to an incompatible value type )
// Boxing
int k = 2;
// The following line boxes i.object o = k;
// Unboxing
int j = (int) o; // that creates InvalidCastException: int j = (short) o;
Let to look in the output wich is produced by the following two examples:
//1
struct Foo {
public int x;
public Foo(int x) {
this.x = x;
}
}
Foo p = new Foo(1); object o = p;
p.x = 2;
Console.WriteLine(((Foo
)o).x);
the output is 1 .unboxing is taking place becouse we have value and reference type. Structure is value type
//2
class Foo {
public int x;
public Foo(int x) {
this.x = x;
}
}
Foo p = new Foo(1); object o = p;
p.x = 2;
Console.WriteLine(((Foo
)o).x);
the output is 2 .There is not unboxing in this case becouse we have two reference types.Class is reference type. So we have assignment of pointers!!
At the end be carefull when use the == operator for reference type:
int i =2;
object o1 = i;
object o2 = i;
Console.WriteLine(o1 == o2);
the output is false becouse although have the same value they don't have the same adrress in stack.
On the other hand onsole.WriteLine(o1.Equals(o2)); will produce true on the output.
If its a object type then “==” compares if the object references are same while “.Equals()” compares if the contents are same.
No comments:
Post a Comment