Lesson 37 +10 XP

C# Interfaces

C# Interfaces

An interface is a contract: it lists what a class must do, but not how. Interfaces contain only declarations, no implementation.

Declaring an interface

Interfaces are declared with interface and named starting with an I by convention:

interface IAnimal
{
  void animalSound();   // interface method - no body
}

Implementing an interface

A class implements an interface with the same : syntax:

class Pig : IAnimal
{
  public void animalSound()
  {
    Console.WriteLine("The pig says: wee wee");
  }
}

class Program
{
  static void Main(string[] args)
  {
    Pig myPig = new Pig();
    myPig.animalSound();
  }
}

Interface rules

  • Like abstract classes, you cannot create objects from interfaces.
  • Interface methods have no body - the implementing class provides it.
  • Interface methods are public by default; the implementation must be public.
  • A class must implement all members of the interface.

Multiple interfaces

A class can implement several interfaces (this gets around single class inheritance):

interface IFirst { void myMethod(); }
interface ISecond { void myOtherMethod(); }

class Demo : IFirst, ISecond
{
  public void myMethod() { ... }
  public void myOtherMethod() { ... }
}

Interface vs abstract class

  • Interface: pure contract - only declarations. Can implement many.
  • Abstract class: can have implemented methods + abstract ones. Only one base class.

TL;DR

  • An interface declares what a class must do.
  • class Pig : IAnimal implements it.
  • Interfaces support multiple inheritance of contracts.
  • No bodies allowed - implementations live in the class.