Upcasting and Downcasting:
Upcasting: Casting from Derived-Class to Base Class
Downcasting: Casting from Base Class to Derived Class
Let's understand the same as an example:
Consider two classes Shape as My parent class and Circle as a Derived class, defined as follows:
class Shape
{
public int Width { get; set; }
public int Height { get; set; }
}
class Circle : Shape
{
public int Radius { get; set; }
public bool FillColor { get; set; }
}
Upcasting:
Shape s = new Shape();
Circle c= s;
Both c and s are referencing to the same memory location, but both of them have different views i.e using "c" reference you can access all the properties of the base class and derived class as well but using "s" reference you can access properties of the only parent class.
A practical example of upcasting is Stream class which is baseclass of all types of stream reader of .net framework:
StreamReader reader = new StreamReader(new FileStreamReader());
here, FileStreamReader() is upcasted to streadm reder.
Downcasting:
Shape s = new Circle();
here as explained above, view of s is the only parent, in order to make it for both parent and a child we need to downcast it
var c = (Circle) s;
The practical example of Downcasting is button class of WPF.
Employee emp= mgr;
should suffice. – Aha