C# ยท Chapter 37 of 46

C# Interfaces

An interface defines a contract of methods and properties that implementing classes must provide, without specifying how they work. Interfaces are declared with the `interface` keyword and conventionally start with a capital I, like IShape.

Unlike classes, a class can implement multiple interfaces in C#, making interfaces a powerful way to achieve flexible, multiple-inheritance-like designs.

Syntax
interface IName {
  void Method();
}
class MyClass : IName {
  public void Method() { }
}

Defining and implementing interfaces

An interface lists method signatures without implementations. A class implements an interface using the colon syntax and must provide implementations for every member.

Interfaces vs abstract classes

A class can implement many interfaces but inherit from only one base class. Interfaces define a pure contract, while abstract classes can also share implementation and state.

Example 1 (csharp)
using System;

interface IShape {
  double Area();
}

class Rectangle : IShape {
  public double Width, Height;
  public Rectangle(double w, double h) { Width = w; Height = h; }
  public double Area() { return Width * Height; }
}

class Program {
  static void Main() {
    IShape shape = new Rectangle(3, 4);
    Console.WriteLine(shape.Area());
  }
}
Output
12

Rectangle implements the IShape interface by providing its own Area() method.

Example 2 (csharp)
using System;

interface IFlyable { void Fly(); }
interface ISwimmable { void Swim(); }

class Duck : IFlyable, ISwimmable {
  public void Fly() { Console.WriteLine("Flying"); }
  public void Swim() { Console.WriteLine("Swimming"); }
}

class Program {
  static void Main() {
    Duck d = new Duck();
    d.Fly();
    d.Swim();
  }
}
Output
Flying
Swimming

Duck implements two interfaces, gaining both behaviors at once.

Key points

  • An interface defines a contract of members without implementation.
  • A class can implement multiple interfaces, unlike class inheritance.
  • Implementing classes must provide code for every interface member.
  • Interface names conventionally start with a capital I.
๐Ÿ’ก Note: Interfaces are ideal for defining capabilities (like IComparable or IDisposable) that unrelated classes can share.

๐Ÿ“ Quick Quiz

1. Can a C# class implement more than one interface?

2. What must an implementing class do for every interface member?

3. What is the naming convention for interfaces?