C# - Interfaces


Interfaces in C# define a contract that classes can implement, ensuring they provide specific functionality. They contain method, property, event, or indexer definitions without implementation, leaving it to the implementing class to define the actual code.

Here's a basic example:

// Define an interface 
public interface IShape 
{ 
    double CalculateArea(); 
    void Display(); 
} 
    
// Implement the interface in a class
public class Circle : IShape 
{
    private double radius; 
    public Circle(double radius) 
    { 
        this.radius = radius; 
    } 
    
    public double CalculateArea() 
    { 
        return Math.PI * radius * radius; 
    } 
    
    public void Display() 
    { 
        Console.WriteLine($"Circle with radius {radius}, Area: {CalculateArea()}"); 
    } 
}

public class Rectangle : IShape 
{
    private double length;
    private double width;
    
    public Rectangle(double length, double width) 
    { 
        this.length = length; 
        this.width = width;
    }
    
    public double CalculateArea() {
        return length * width; 
    } 
    
    public void Display() { 
        Console.WriteLine($"Rectangle with length {length} and width {width}, Area: {CalculateArea()}");
    } 
}

In this example, IShape is an interface that declares CalculateArea() and Display() methods. Both Circle and Rectangle classes implement this interface by providing their own implementations for these methods.

Usage:

IShape circle = new Circle(5); 
circle.Display(); 

// Outputs: Circle with radius 5, Area: 78.53981633974483 

IShape rectangle = new Rectangle(4, 6); 
rectangle.Display(); 
// Outputs: Rectangle with length 4 and width 6, Area: 24

Interfaces are powerful because they allow you to create code that's more flexible, allowing different classes to share common methods or behaviors while still having their own unique implementations.