uppercasting and downcasting in c#

indradaman sharma
indrada...
116 Points
14 Posts

Hello sir,

Can you please explain to me what is uppercasting and downcasting in c#.

Views: 8941
Total Answered: 3
Total Marked As Answer: 0
Posted On: 20-Apr-2017 02:36

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
4918 Points
28 Posts
         

Consider following  two examples

  1. 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.
  2. 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
chkdk
chkdk
46 Points
2 Posts
         
class Employee : Person
{

}

// downcasting
Person p= new Person();
Employee e = p as Employee;

//upcasting
Employee e  = new Employee();
Person p = e as Person;
Posted On: 05-May-2017 02:00
Jak
Jak
908 Points
132 Posts
         
  • Upcasting is an operation that creates a base class reference from a subclass reference. (subclass -> superclass) (i.e. Manager -> Employee)
  • downcasting is an operation that creates a subclass reference from a base class reference. (superclass -> subclass) (i.e. Employee -> Manager)
Posted On: 05-May-2017 02:12
 Log In to Chat