CSharp - What is the output: Downcasting is unsafe

Question

What is the output from the following code

using System;
class Shape
{
    public void ShowMe()
    {
        Console.WriteLine("Shape.ShowMe");
    }
}
class Circle : Shape
{
    public void Area()
    {
        Console.WriteLine("Circle.Area");
    }
}
class Rectangle : Shape
{
    public void Area()
    {
        Console.WriteLine("Rectangle.Area");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Circle circleOb = new Circle();
        Rectangle rectOb = new Rectangle();
        Shape[] shapes = { circleOb, rectOb };
        Circle circleOb2 = (Circle)shapes[1];//Incorrect
                                             //Circle circleOb2 = (Circle)shapes[0];//Correct
        circleOb2.Area();
    }
}


Click to view the answer

A runtime exception will be thrown.

Note

This is an example where we can encounter InvalidCastException() at runtime.

Shape was a Rectangle object , not a Circle object.

Related Quiz