C#

Contributed by Chris Rathman

Shape class (shape.cs)

 ```using System; namespace Polymorph { public abstract class Shape { private int x; private int y; // constructor public Shape(int newx, int newy) { setX(newx); setY(newy); } // accessors for x & y coordinates public int getX() { return x; } public int getY() { return y; } public void setX(int newx) { x = newx; } public void setY(int newx) { y = newx; } // move the x & y coordinates public void moveTo(int newx, int newy) { setX(newx); setY(newy); } public void rMoveTo(int deltax, int deltay) { moveTo(deltax + getX(), deltay + getY()); } // virtual routine - draw the shape public abstract void draw(); } } ```

Rectangle class (rectangle.cs)

 ```using System; namespace Polymorph { public class Rectangle: Shape { private int width; private int height; // constructor public Rectangle(int newx, int newy, int newwidth, int newheight): base(newx, newy) { setWidth(newwidth); setHeight(newheight); } // accessors for width & height public int getWidth() { return width; } public int getHeight() { return height; } public void setWidth(int newwidth) { width = newwidth; } public void setHeight(int newheight) { height = newheight; } // draw the rectangle public override void draw() { Console.WriteLine("Drawing a Rectangle at:({0},{1}), Width {2}, Height {3}", getX(), getY(), getWidth(), getHeight()); } } } ```

Circle class (circle.cs)

 ```using System; namespace Polymorph { public class Circle: Shape { private int radius; // constructor public Circle(int newx, int newy, int newradius): base(newx, newy) { setRadius(newradius); } // accessors for the radius public int getRadius() { return radius; } public void setRadius(int newradius) { radius = newradius; } // draw the circle public override void draw() { Console.WriteLine("Drawing a Circle at:({0},{1}), Radius {2}", getX(), getY(), getRadius()); } } } ```

Try shapes function (polymorph.cs)

 ```using System; namespace Polymorph { class Polymorph { static void Main(string[] args) { Shape[] scribble = new Shape[2]; Rectangle rect; // create some shape instances scribble[0] = new Rectangle(10, 20, 5, 6); scribble[1] = new Circle(15, 25, 8); // iterate through the list and handle shapes polymorphically for (int i = 0; i < scribble.Length; i++) { scribble[i].draw(); scribble[i].rMoveTo(100, 100); scribble[i].draw(); } // call a rectangle specific function rect = new Rectangle(0, 0, 15, 15); rect.setWidth(30); rect.draw(); } } } ```

Output

 ```Drawing a Rectangle at:(10,20), Width 5, Height 6 Drawing a Rectangle at:(110,120), Width 5, Height 6 Drawing a Circle at:(15,25), Radius 8 Drawing a Circle at:(115,125), Radius 8 Drawing a Rectangle at:(0,0), Width 30, Height 15 ```

Chris Rathman / Chris.Rathman@tx.rr.com