Dangerous downcasting

Run Settings
LanguageC#
Language Version
Run Command
using System; using System.Collections.Generic; using System.Linq; class Shape { public void Draw() { Console.WriteLine("Drawing a shape"); } } class Circle : Shape { public void DrawCircle() { Console.WriteLine("Drawing a circle"); } } class Square : Shape { public void DrawSquare() { Console.WriteLine("Drawing a square"); } } class Program { static void Main(string[] args) { Shape shape = new Circle(); // Shape shape = new Square(); // Upcasting: Creating a base class reference to a derived class object // Downcasting: Converting the base class reference back to a derived class reference Circle circle = (Circle)shape; var x = (Square)shape; // Checking if the downcast is successful if (circle != null) { circle.DrawCircle(); } else { Console.WriteLine("Downcast failed"); } } }
Editor Settings
Theme
Key bindings
Full width
Lines