Skip to content

Interfaces

An interface defines a contract β€” a set of members (methods, properties, events) that any implementing class or struct must provide β€” without dictating how they’re implemented. Unlike class inheritance, a type can implement multiple interfaces, making interfaces C#β€˜s primary tool for polymorphism across unrelated class hierarchies.

public interface IShape
{
double GetArea();
}
public interface IDrawable
{
void Draw();
}
// A class can implement multiple interfaces
public class Circle : IShape, IDrawable
{
public double Radius { get; set; }
public double GetArea() => Math.PI * Radius * Radius;
public void Draw() => Console.WriteLine("Drawing a circle");
}
IShape shape = new Circle { Radius = 5 };
Console.WriteLine(shape.GetArea()); // works through the interface reference
List<IShape> shapes = new() { new Circle { Radius = 2 }, new Circle { Radius = 3 } };
double totalArea = shapes.Sum(s => s.GetArea());

Forgetting that interface members are implicitly public and can’t have an access modifier in the implementing class’s declaration matching anything but public β€” trying to implement an interface method as private fails to satisfy the contract.

public interface IShape
{
double GetArea();
}
public class Circle : IShape
{
private double GetArea() => Math.PI * 25; // Error: Circle does not implement IShape.GetArea()
}
// Fix: interface implementations must be public
public class Circle : IShape
{
public double GetArea() => Math.PI * 25;
}
  1. Can a C# class implement more than one interface?

    AnswerYes β€” unlike single class inheritance, a class can implement any number of interfaces.
  2. What access modifier must a class’s implementation of an interface member use?

    Answerpublic β€” interface members are implicitly public contracts, and implementations must be publicly accessible to satisfy them.
  3. Why prefer coding against an interface type (like IShape) rather than a concrete class type?

    AnswerIt decouples your code from any specific implementation β€” you can swap in any class that implements the interface (for testing, extension, or future changes) without modifying the code that depends on it.