Saturday, June 27, 2026

C# Example of Interface as Method Return Type

Example of Interface as Method Return Type: If class implements an interface then the object of that class can be returned as method return type which is that interface. In the following example, GetShape method can return an object which class implements IShape interface. Here, Triangle, Rectangle and Hexagon classes implements IShape interface. Therefore, GetShape method can return an object of Triangle, Rectangle or Hexagon classes.
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 IShape GetShape(int count)
    {
        switch (count)
        {
            case 3:
                return new Triangle();
            case 4:
                return new Rectangle();
            case 6:
                return new Hexagon();
            default:
                throw new Exception("No shape found.");
        }
    }
    public void Info(int points)
    {
        IShape shape = GetShape(points);
        Console.WriteLine(shape.GetType() + " has " + shape.NumberOfPoints + " points.");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Shape shape = new Shape();
        shape.Info(3);
        shape.Info(4);
        shape.Info(6);
        shape.Info(7);
    }
}
OUTPUT
Triangle has 3 points.
Rectangle has 4 points.
Hexagon has 6 points.
Unhandled exception. System.Exception: No shape found.
 

No comments:

Post a Comment

Hot Topics