Saturday, June 27, 2026

C# Example of Interface as Method Parameter

Example of Interface as Method Parameter: If class implements an interface then the object of that class can be passed as argument to the method parameter which type is the interface.
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 Shape
{
    public void GetPointCount(IShape shape)
    {
        Console.WriteLine($"{shape.GetType()} has {shape.NumberOfPoints} number of points.");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Shape shape = new Shape();
        shape.GetPointCount(new Triangle());
        shape.GetPointCount(new Rectangle());
        shape.GetPointCount(new Hexagon());
    }
}
OUTPUT
Triangle has 3 number of points.
Rectangle has 4 number of points.
Hexagon has 6 number of points.

No comments:

Post a Comment

Hot Topics