Saturday, June 27, 2026

C# Example of Array of Interface Type

Array of Interface Type: If classes A, B and C implements an interface I then an array of interface denoted by I[] can be initialized as follows
I[] arr = {new A(), new B(), new C()};
Example
interface IShape
{
    int NumberOfPoints { get; }
}
class Triangle : IShape
{
    int _numberOfPoints = 3;
    public int NumberOfPoints { get => _numberOfPoints; }
}
class Rectangle : IShape
{
    int _numberOfPoints = 4;
    public int NumberOfPoints { get => _numberOfPoints; }
}
class Hexagon : IShape
{
    int _numberOfPoints = 6;
    public int NumberOfPoints { get => _numberOfPoints; }
}
class Program
{
    static void Main(string[] args)
    {
        // array of interface where each element is an object,
        // which class implements the inetrface
        IShape[] shapes = { new Triangle(), new Rectangle(), new Hexagon() };
        foreach (var shape in shapes)
        {
            Console.WriteLine($"{shape.GetType()} has {shape.NumberOfPoints} points.");
        }
    }
}
OUTPUT
Triangle has 3 points.
Rectangle has 4 points.
Hexagon has 6 points.

No comments:

Post a Comment

Hot Topics