Interfaces in C#

Interfaces are named collections of method signatures.

using System;

// Here's a basic interface for geometric shapes.
public interface IGeometry
{
    double Area();
    double Perimeter();
}

// For our example we'll implement this interface on
// Rectangle and Circle types.
public class Rectangle : IGeometry
{
    public double Width { get; set; }
    public double Height { get; set; }

    // To implement an interface in C#, we just need to
    // implement all the methods in the interface.
    public double Area()
    {
        return Width * Height;
    }

    public double Perimeter()
    {
        return 2 * Width + 2 * Height;
    }
}

public class Circle : IGeometry
{
    public double Radius { get; set; }

    // The implementation for Circle.
    public double Area()
    {
        return Math.PI * Radius * Radius;
    }

    public double Perimeter()
    {
        return 2 * Math.PI * Radius;
    }
}

public class Program
{
    // If a parameter has an interface type, then we can call
    // methods that are in the named interface. Here's a
    // generic Measure method taking advantage of this
    // to work on any IGeometry.
    static void Measure(IGeometry g)
    {
        Console.WriteLine(g);
        Console.WriteLine(g.Area());
        Console.WriteLine(g.Perimeter());
    }

    public static void Main()
    {
        var r = new Rectangle { Width = 3, Height = 4 };
        var c = new Circle { Radius = 5 };

        // The Circle and Rectangle types both
        // implement the IGeometry interface so we can use
        // instances of these types as arguments to Measure.
        Measure(r);
        Measure(c);
    }
}

When you run this program, you should see output similar to this:

Rectangle
12
14
Circle
78.53981633974483
31.41592653589793

In C#, interfaces are a fundamental part of the language and are used extensively for achieving polymorphism and defining contracts that classes must adhere to. They allow for more flexible and maintainable code by enabling loose coupling between components.

To learn more about C#’s interfaces, you can refer to the official Microsoft documentation on Interfaces.