LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 2718 min read

Interfaces

Learn how interfaces define contracts that unrelated classes can implement in C#.

What is an Interface?

An interface defines a contract — a set of methods and properties a class promises to implement — without providing any implementation itself. By convention, interface names start with a capital "I", like `IShape` or `IComparable`.

Implementing an Interface

interface IShape
{
double GetArea();
}
class Square : IShape
{
public double Side;
public Square(double side) { Side = side; }
public double GetArea() => Side * Side;
}
IShape shape = new Square(4);
Console.WriteLine(shape.GetArea());
Output

Click Run to see what this code prints.

Multiple Interfaces

Unlike class inheritance, a class can implement as many interfaces as it needs — this is how C# achieves the flexibility of multiple inheritance without its complications.

interface IFlyable { void Fly(); }
interface ISwimmable { void Swim(); }
class Duck : IFlyable, ISwimmable
{
public void Fly() => Console.WriteLine("Duck is flying");
public void Swim() => Console.WriteLine("Duck is swimming");
}

FAQs

Since C# 8, yes — "default interface methods" allow this, though it's used sparingly, mostly for evolving public interfaces without breaking existing implementers.

Summary

  • Interfaces define a contract without implementation.
  • A class can implement multiple interfaces, unlike single class inheritance.
  • Programming against an interface type keeps code flexible and decoupled.
Next Lesson →

Static Members