publicclassShape { // A few example members publicint X { get; privateset; } publicint Y { get; privateset; } publicint Height { get; set; } publicint Width { get; set; } // Virtual method publicvirtualvoidDraw() { Console.WriteLine("Performing base class drawing tasks"); } }
classCircle : Shape { publicoverridevoidDraw() { // Code to draw a circle... Console.WriteLine("Drawing a circle"); base.Draw(); } } classRectangle : Shape { publicoverridevoidDraw() { // Code to draw a rectangle... Console.WriteLine("Drawing a rectangle"); base.Draw(); } } classTriangle : Shape { publicoverridevoidDraw() { // Code to draw a triangle... Console.WriteLine("Drawing a triangle"); base.Draw(); } }
classProgram { staticvoidMain(string[] args) { // Polymorphism at work #1: a Rectangle, Triangle and Circle // can all be used whereever a Shape is expected. No cast is // required because an implicit conversion exists from a derived // class to its base class. var shapes = new List<Shape> { new Rectangle(), new Triangle(), new Circle() };
// Polymorphism at work #2: the virtual method Draw is // invoked on each of the derived classes, not the base class. foreach (var shape in shapes) { shape.Draw(); }
// Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }