Interfaces
Interfaces
Section titled βInterfacesβWhat it means
Section titled βWhat it meansβ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.
Examples
Section titled βExamplesβpublic interface IShape{ double GetArea();}
public interface IDrawable{ void Draw();}
// A class can implement multiple interfacespublic 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());Common mistake
Section titled βCommon mistakeβ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 publicpublic class Circle : IShape{ public double GetArea() => Math.PI * 25;}Quick practice
Section titled βQuick practiceβ-
Can a C# class implement more than one interface?
Answer
Yes β unlike single class inheritance, a class can implement any number of interfaces. -
What access modifier must a classβs implementation of an interface member use?
Answer
publicβ interface members are implicitly public contracts, and implementations must be publicly accessible to satisfy them. -
Why prefer coding against an interface type (like
IShape) rather than a concrete class type?Answer
It 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.