Consider following two examples
-
class Employee
{
// some code
}
class Manager : Employee
{
//some code
}
class Lead : Employee
{
//some code
}
Above we have three classes. Employee is the base class for Manager and Lead. Manager and Lead are derived classes.
-
class Shape
{
// some code
}
class Squire : Shape
{
//some code
}
class Circle : Shape
{
//some code
}
Here we derived classes Squire and Circle from Shape
Up-Casting
Assignment of derived class object to a base class is known as up-casting. As, Up-casting is implicit any explicit typecast is not required.
For examples
Manager mgr = new Manager();
Lead ld = new Lead();
Employee emp1 = mgr;
Employee emp2 = ld;
Squire sqr = new Squire();
Circle crl = new Circle();
Shape shp1 = sqr;
Shape shp2 = crl;
Down-Casting
Assignment of base class object to derived class object is known as Down-casting. In Down-casting explicit typecast is required. Down-Casting may throw InvalidCastException.
For examples
if (employee is Manager)
{
Manager m = (Manager)employee;
//do something with it
}
//OR with the as operator like this:
Manager m = (employee as Manager);
if (m != null)
{
//do something with it
}
Posted On:
20-Apr-2017 06:24