Light Mode Image

C# Interface

An interface in C# is a way to define a contract for a class. It specifies a set of methods, properties, events, or indexers that a class must implement.

 

An interface itself does not provide any implementation; it only defines the structure that must be followed by the classes that implement it.

 

Basic example of an interface.

// Define an interface named IShape
public interface IShape
{
    // Method to calculate the area
    double CalculateArea();

    // Property for getting the shape's name
    string ShapeName { get; set; }
}

// Implement the interface in a class
public class Circle : IShape
{
    // Properties
    public double Radius { get; set; }
    public string ShapeName { get; set; }

    // Constructor
    public Circle(double radius)
    {
        Radius = radius;
        ShapeName = "Circle";
    }

    // Implement the CalculateArea method from the interface
    public double CalculateArea()
    {
        return Math.PI * Math.Pow(Radius, 2);
    }
}

class Program
{
    static void Main()
    {
        // Create an instance of the Circle class
        Circle myCircle = new Circle(5);

        // Use the CalculateArea method from the interface
        Console.WriteLine($"Area of {myCircle.ShapeName}: {myCircle.CalculateArea()}");

        // Output: Area of Circle: 78.53981633974483
    }
}

 

In this example, IShape is an interface that declares a method (CalculateArea) and a property (ShapeName). 

 

The Circle class implements this interface by providing concrete implementations for the methods and properties declared in the interface.

 

The Main method demonstrates how to use the interface by creating an instance of the Circle class and invoking the CalculateArea method. Interfaces are useful for achieving abstraction, enabling code to be more modular, and facilitating polymorphism in C#.