Is as
1 2 3 4 5 6 |
Shape[] shapes = { new Triangle("Triangle"), new Hexagon("Hexagon"), new Circle("Circle") }; for (int i = 0; i < shapes.Length; i++) { if (shapes[i] is IPointy) Console.WriteLine("Points in " + shapes[i].Name +" "+ (shapes[i] as IPointy).Points); else Console.WriteLine("Ipointy not supported in "+shapes[i].Name); } Console.ReadLine(); |
try catch – not best variant
1 2 3 4 5 6 7 |
Circle c1 = new Circle("Circle"); IPointy itf = null; try { itf = (IPointy)c1; } catch (InvalidCastException e) { Console.WriteLine(e.Message); } Console.ReadLine(); |
123
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Interace { class Program { static void Main(string[] args) { Triangle t = new Triangle("Triangle"); t.Draw(); Hexagon h = new Hexagon("Hexagon"); h.Draw(); Circle c = new Circle("Circle"); c.Draw(); // another example Shape[] shapes = { new Triangle("Triangle"), new Hexagon("Hexagon"), new Circle("Circle") }; for (int i = 0; i < shapes.Length; i++) { if (shapes[i] is IPointy) Console.WriteLine("Points in " + shapes[i].Name +" "+ (shapes[i] as IPointy).Points); else Console.WriteLine("Ipointy not supported in "+shapes[i].Name); } Console.ReadLine(); } // base class public class Shape { public string Name { get; set; } public Shape(string name) { Name = name; } public Shape() { } public virtual void Draw() { } } //declaring interface public interface IPointy { byte Points { get; } } // Triangle - derived from shape and implementing IPointy public class Triangle : Shape, IPointy { public Triangle() { } public Triangle(string name) : base(name) { } public override void Draw() { Console.WriteLine("Shape name is {0}",this.Name); } public byte Points { get { return 3; } } } // Hexagon - derived from shape and implementing IPointy public class Hexagon : Shape, IPointy { public Hexagon() { } public Hexagon(string name) : base(name) { } public override void Draw() { Console.WriteLine("Shape name is {0}", this.Name); } public byte Points { get { return 6; } } // << another implementation of IPointy } // // Circle - derived from shape and NOT implementing IPointy public class Circle : Shape { public Circle() { } public Circle(string name) : base(name) { } public override void Draw() { Console.WriteLine("Shape name is {0}", this.Name); } } } } |