Interfaces

View saved

Declare an interface

Interfaces describe what a type can do, not how.

interface ILogger
{
    void Log(string message);
}

class ConsoleLogger : ILogger
{
    public void Log(string message) => Console.WriteLine(message);
}

Depend on the interface

Methods can accept the interface type for flexibility.

void Run(ILogger logger) => logger.Log("running");
Run(new ConsoleLogger());

Multiple interfaces

A class may implement several interfaces.

Interface habits

  • Name interfaces with a leading I by convention
  • Keep interfaces small and focused
  • Default interface methods exist but beginners can skip them
  • Prefer interfaces at boundaries: logging, storage, clocks

Comments

One comment per signed-in account. Comments are saved with this page’s URL.