September 23, 2007
Hi Guys
NP43 Up-casting and Down-casting
What is meant by Up-casting and Down-casting in C#? Anyone knows please explain.
September 23, 2007
Hi Guys
NP43 Up-casting and Down-casting
What is meant by Up-casting and Down-casting in C#? Anyone knows please explain.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Posted Sep 23, 2007, 1:25 PM
Thank you very much for your explanation Alan
AlanPosted Sep 23, 2007, 11:07 AM
Upcasting means converting a child class reference into a parent class reference. For example:
Child c1 = new Child();
Child c2 = new Child();
Parent p1 = c1; // implicit upcast
Parent p2 = (Parent)c2; // explicit upcast
In these two cases, the compiler knows that it is always safe to cast from a Child class to a parent class because a Child is a Parent - in other words Child contains all the members that Parent contains.
Upcasting is no called because you're casting up the object hierarchy (i.e. towards System.Object which sits at the top).
Downcasting means converting a parent class reference into a child class reference. For example:
Child c1 = new Child();
Parent p1 = c1;
Child c2 = (Child)p1; // downcast, succeeds at runtime
Parent p2 = new Parent();
Child c3 = p2; // attempted downcast, fails at compile time
Child c4 = (Child)p2; // attempted downcast, fails at runtime
The only siutation where downcasting is legal is if a Parent variable actually contains a reference to a Child object. The compiler knows that this is a possibility and so allows the two downcasts to c2 and c4. However, the c4 cast fails at runtime because the parent variable p2 actually contains a reference to a Parent object, not a Child object.
A cast from a Parent class to a Child class doesn't work because the Parent class doesn't (or doesn't necessarily) contain all the members that the Child contains.
Downcasting is no called because you're casting down the object hierarchy (i.e. away from System.Object).
Notice that with reference types casting doesn't actually change the type of the object. It just enables them to be regarded as being of some other type.