CSharp examples for Custom Type:Polymorphism
Down Casting Rectangles
using System;//from ww w . j a va2 s . c o m abstract public class Shape { public abstract void DrawYourself(); } public class Rectangle : Shape { private double height; public Rectangle(double initialHeight) { height = initialHeight; } public override void DrawYourself() { Console.WriteLine("Draw a rectangle"); } public double Height { get { return height; } set { height = value; } } } class Circle : Shape { public override void DrawYourself() { Console.WriteLine("Draw a circle"); } } class Tester { private static Shape[] drawing; public static void Main() { Rectangle myRectangle; double totalHeight = 0; drawing = new Shape[3]; drawing[0] = new Rectangle(10.6); drawing[1] = new Circle(); drawing[2] = new Rectangle(30.8); for(int i = 0; i < drawing.Length; i++) { if(drawing[i] is Rectangle) { myRectangle = (Rectangle)drawing[i]; totalHeight += myRectangle.Height; } } Console.WriteLine("Total height of rectangles: {0}", totalHeight); } }