Monday, November 22, 2010

upcasting and downcasting

upcasting - is possible, its implicit coversion and is safe. (ie,  A aa=new B() - is upcasting. Here were are converting from Type B to Type A. It is possible, because A is the base class. And all the base class methods and properties will be available in object aa). Its called upcasting because we more moving up the object hierarchy.

downcasting - is explicit conversion and is unsafe. you will have to be very careful while downcasting types.  Its called downcasting because we are moving down the object hierarchy.


(with sample: class A, class A:B, class C:B)

Class A
{
}

Class B:A
{
}

Class C:B
{
}


Question:
A aa=new B();       // is this possible? Ans:
A aa=new C();       // is this possible? Ans:
B bb=new A();       // is this possible? Ans:
B bb=(B)new A();  // is this possible? Ans:


Solution

A aa = new B(); // is possible.

Implicit conversion from Type B to Type A is possible. Because Type A is the base class and Type B is derived from Type A.

//B bb = new A();   //compile Error : Cannot implicitly convert type 'A' to 'B'. An explicit conversion exists


//B bb = (B) new A(); //runtime Error : System.InvalidCastException - Unable to cast object of type 'A' to type 'B'



Hint:

Car c=new BMW();   //possible
BMW b=new Car();  //not possible, compile error - implicit conversion not possible from type Car to BMW
BMW_E_Series be=new Car(); //not possible, compile error
BMW_E_Series be= (BMW_E_Series) new Car(); //runtime error, explicit conversion not possible


Reference:

http://www.c-sharpcorner.com/UploadFile/pcurnow/polymorphcasting06222007131659PM/polymorphcasting.aspx

No comments: