Consider we are having three classes, Shape which is the base class and two other classes Circle and Text that inherits from the base classe (Shape)
Shape.cs
namespace ObjectOriented
{
public class Shape
{
public int Height { get; set; }
public int Width { get; set; }
public int X { get; set; }
public int Y { get; set; }
public void Draw()
{
}
}
}
Text.cs
using System;
namespace ObjectOriented
{
public class Text : Shape
{
public string FontType { get; set; }
public int FontSize { get; set; }
public void Weirdo()
{
Console.WriteLine("Weird stuff");
}
}
}
Circle.cs
namespace ObjectOriented
{
public class Circle : Shape
{
}
}
we all know that Upcasting always succeed and that we create a reference to a base class from a subclass reference
Text txt = new Text();
Shape shape = txt //upcast
and downcasting may throw and InvalidCastException for example
Text txt = new Text();
Shape shape = txt; //upcast
Circle c = (Circle)shape; //DownCast InvalidCastException
what i'm confused about is that what are the situations/cases that we might need to up/down cast and object ?