Start learning free

LESSON 189 OF 347 · OBJECT-ORIENTED PROGRAMMING

Interfaces in C#: Contracts with the interface Keyword

Lesson Read the full explanation

TL ; DR:

An interface is a pure contract — a list of methods that a class promises to implement, with no shared data and no shared code. Unlike inheritance ("is a"), interfaces express "can do".


interface ISpeaker {
    void Speak();
}
class Dog : ISpeaker {
    public void Speak() {
        Console.WriteLine("Woof");
    }
}


Full lesson:

An interface defines what a class can do, not how it does it or what it is. A Truck, a Robot, and a Drone aren't the same kind of thing — but they can all Move(). You'd put Move() in a Movable interface and have each one implement it.

Interface vs abstract class

Abstract classInterface
Has fieldsYesUsually no
Has method bodiesYes (some)No (or default impls only)
Multiple "inheritance"Usually noYes — a class can implement many interfaces
Models"is a""can do"

A class inherits from at most one parent class but can implement many interfaces. That's why interfaces are the right tool for cross-cutting capabilities like Comparable, Serializable, Iterable, etc.

The language landscape

  • C# / Java — first-class interface keyword. C# uses : for both inheritance and implementation; Java uses extends for inheritance and implements for interfaces.
  • Python — no separate interface; abstract base classes (ABCs) with all-abstract methods serve the same role.
  • JavaScript — no interface keyword in plain JS (TypeScript has it). The convention is a stub class.
  • C++ — a class with only pure-virtual methods is an interface. Multiple inheritance lets a class implement several.

Your task

The Speaker interface (or interface-like base) is already declared. Create a Dog class that implements it, with a speak() method that prints "Woof".

Expected output:

Woof
STEP 1 OF 2
    Ctrl + Enter to check

    C# · OBJECT-ORIENTED PROGRAMMING

    Interfaces in C#, explained

    What an interface is

    An interface is a contract: a list of members that a class promises to provide. It says what a type can do, not how it does it and not what it is. The interface holds no fields and, in everyday use, no method bodies. Each class that signs the contract writes its own bodies.

    A Truck, a Robot and a Drone are different kinds of things, so they don't belong in one inheritance tree. But all three can move. Put Move() in an IMovable interface and let each class implement it. Code that only needs something to move can then work with IMovable and never care which class is behind it.

    Inheritance answers "what is it?" (a puppy is a dog). An interface answers "what can it do?" (a robot can speak).

    The syntax

    interface ISpeaker {
        void Speak();
    }
    
    class Dog : ISpeaker {
        public void Speak() {
            Console.WriteLine("Woof");
        }
    }
    

    Three details are worth noticing:

    • The interface declares the method signature and ends it with a semicolon. There is no body and no access modifier.
    • By convention, interface names start with a capital I: ISpeaker, IMovable, IComparable. The letter tells readers at a glance that a name is a contract rather than a class.
    • C# uses the same colon for inheriting from a class and for implementing an interface. class Dog : ISpeaker says that Dog implements ISpeaker.

    Using the interface as a type

    A variable can have an interface type and hold any object whose class implements it:

    ISpeaker rex = new Dog();
    rex.Speak();   // Woof
    

    Through rex you can call only what ISpeaker declares. If Dog had a Fetch() method, the compiler would reject rex.Fetch(), because the variable's type promises nothing but Speak.

    Implementing several interfaces

    A class can have only one base class, but it can implement as many interfaces as it likes. List them after the colon, separated by commas:

    interface IMovable {
        void Move();
    }
    
    class Robot : IMovable, ISpeaker {
        public void Move()  { Console.WriteLine("Rolling"); }
        public void Speak() { Console.WriteLine("Beep"); }
    }
    

    If a class has a base class as well, the base class comes first in the list: class Puppy : Dog, IMovable. This is why interfaces suit abilities that cut across unrelated classes, such as the standard library's IComparable (can be ordered) and IEnumerable (can be looped over with foreach).

    Interface or abstract class?

    Abstract classInterface
    FieldsYesNo
    Method bodiesYes, for some methodsNormally none; C# 8 and later allow default implementations
    How many a class can haveOne base classAny number
    Models"is a""can do"

    Pick an abstract class when related classes share data or code. Pick an interface when unrelated classes only need to agree on behaviour.

    Common mistakes

    • Forgetting public on the implementing method. Members of a class are private unless marked otherwise, and a class implements an interface member through a public method with a matching signature. Writing void Speak() without public is a compile error.
    • Adding override. Interface methods need no override keyword. Just provide the method. (override belongs to virtual and abstract methods of a base class.)
    • Leaving a member out. A class that lists an interface must implement every member, or the code doesn't compile. Declaring the class abstract is the only way to postpone some of them.
    • Trying to create an interface. new ISpeaker() is an error. You create an object of a class and store it in an interface-typed variable.
    • Different capitalisation or signature. C# is case-sensitive: speak() does not implement Speak(). The return type and parameter list must match too.
    • Putting fields in an interface. An interface can't declare instance fields. If implementers need shared data, use a base class.

    The exercise, step by step

    The lesson gives you the ISpeaker interface and a Solution class whose MainFunction creates a Dog, stores it in an ISpeaker variable and calls Speak(). The expected output is Woof.

    1. Declare Dog and list the interface. Write class Dog : ISpeaker below the interface. The colon is what ties the class to the contract.
    2. Implement Speak. Add a public void Speak() method that writes Woof with Console.WriteLine. It must be public and match the interface's signature exactly.

    The finished code:

    interface ISpeaker {
        void Speak();
    }
    
    class Dog : ISpeaker {
        public void Speak() {
            Console.WriteLine("Woof");
        }
    }
    
    class Solution {
        public void MainFunction() {
            ISpeaker rex = new Dog();
            rex.Speak();
        }
    }
    

    The call rex.Speak() looks only at the interface type to decide it is allowed, and at the actual object to decide what runs. The object is a Dog, so Dog's body prints Woof. Add a second class that implements ISpeaker and the same call would run its body instead.

    Key takeaways

    • An interface lists members a class must provide; it models "can do".
    • Name interfaces with a leading I, and implement them with class Name : IName.
    • Implementing methods must be public and match the signature; no override is needed.
    • A class has one base class but may implement many interfaces.
    • A variable of an interface type can hold any implementing object, and only the interface's members can be called through it.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free