Upcasting Downcasting - VishalBhanderi31/C-Sharp-OOPS GitHub Wiki

Agenda

  • Conversion from a derived class to a base class (Upcasting or Implicit)
  • Conversion from a base class to derived class (Downcasting - Explicit)
  • The as and is keywords

public class Shape
{
}

public class Circle : Shape
{
}

**Upcasting**
Circle circle = new Circle();
Shape shape = circle;

**Downcasting**
Circle anotherCircle = (Circle)shape;
It throws an InvalidCastException To Prevent this happening we use "as" keyword

Instead of this,
Car car = (Car) obj;
we can use like below to get rid of Exception
Car car = obj as Carl; // If it can not convert than return null
if(car != null)
{
}

We also have is Keyword, with the help od is the keyword we can check the type of an object. if(obj as Car)
{
Car car = (Car) obj;
...
}