AnyCompiler

Interfaces

An interface defines a set of methods a class must implement. Unlike a base class, a class can implement multiple interfaces at once, and completely unrelated classes — Circle and Square here share nothing but IShape — can all satisfy the same interface.

using System;

interface IShape {
    double Area();
}

class Circle : IShape {
    public double Radius;
    public Circle(double r) { Radius = r; }
    public double Area() { return Math.PI * Radius * Radius; }
}

class Square : IShape {
    public double Side;
    public Square(double s) { Side = s; }
    public double Area() { return Side * Side; }
}

class Program {
    static void Main() {
        IShape[] shapes = { new Circle(2), new Square(3) };
        foreach (IShape s in shapes) {
            Console.WriteLine(s.Area());
        }
    }
}
Output
12.5663706143592
9

shapes is an array of IShape — the interface type — but each element still calls the correct class's own Area() implementation. This is dynamic dispatch: which method actually runs is decided at runtime based on the object's real class.

Next: structs and value types — C#'s genuinely distinctive value-type semantics, where copying actually copies.

Practice exercise

Define an interface INamed with a method GetName(). Define a class Dog that implements INamed, with a private field and a GetName() method returning it. Write a method Greet(INamed n) that prints "Hello, " + n.GetName(). Call it with a new Dog whose name is "Rex".