Mega Code Archive

 
Categories / C# Tutorial / Class
 

Indexer for generic type

using System.Collections; public abstract class Shape {    public abstract void Draw(); } public class Rectangle : Shape {    public override void Draw()    {       System.Console.WriteLine( "Rectangle.Draw" );    } } public class Circle : Shape {    public override void Draw()    {       System.Console.WriteLine( "Circle.Draw" );    } } public class ShapeList {    private ArrayList shapes;    public ShapeList()    {       shapes = new ArrayList();    }    public int Count    {       get       {          return shapes.Count;       }    }    public Shape this[ int index ]    {       get       {          return (Shape) shapes[index];       }    }    public void Add( Shape shape )    {       shapes.Add( shape );    } } public class MainClass {    static void Main()    {       ShapeList drawing = new ShapeList();       drawing.Add( new Rectangle() );       drawing.Add( new Circle() );              for( int i = 0; i < drawing.Count; ++i ) {          Shape shape = drawing[i];          shape.Draw();       }    } } Rectangle.Draw Circle.Draw