TExcelTAD
Home › C# › C# Interfaces

C# Interfaces

An interface is a contract: a list of members that a type promises to provide. It says what an object can do, without saying how. Any class or struct can implement an interface, and a single type can implement many interfaces — which makes interfaces the main way to share capabilities across unrelated types.

Declaring and implementing an interface

By convention, interface names start with a capital I. Members are implicitly public and usually have no body.

csharp · try it yourself
using System;

IPrintable[] items = { new Invoice(1001, 250m), new Photo("beach.jpg", 1920, 1080) };

foreach (IPrintable item in items)
    item.Print();

interface IPrintable
{
    void Print();
}

class Invoice : IPrintable
{
    private readonly int number;
    private readonly decimal amount;
    public Invoice(int number, decimal amount) { this.number = number; this.amount = amount; }
    public void Print() => Console.WriteLine(
quot;Invoice #{number}: {amount}"); } class Photo : IPrintable { private readonly string file; private readonly int w, h; public Photo(string file, int w, int h) { this.file = file; this.w = w; this.h = h; } public void Print() => Console.WriteLine(
quot;Photo {file} ({w}x{h})"); }
Invoice #1001: 250
Photo beach.jpg (1920x1080)

Invoice and Photo have nothing else in common, yet both can be treated as IPrintable. Implementing a member of an interface does not use the override keyword — you simply write a public member with a matching signature.

Implementing several interfaces

A class can inherit from at most one base class, but it can implement any number of interfaces, listed after the colon:

csharp · try it yourself
using System;

var duck = new Duck();
duck.Swim();
duck.Fly();

ISwimmer swimmer = duck;
IFlyer flyer = duck;
Console.WriteLine(swimmer is IFlyer);
Console.WriteLine(
quot;Max altitude: {flyer.MaxAltitude} m"); interface ISwimmer { void Swim(); } interface IFlyer { int MaxAltitude { get; } void Fly(); } class Animal { public string Kind => GetType().Name; } class Duck : Animal, ISwimmer, IFlyer { public int MaxAltitude => 1000; public void Swim() => Console.WriteLine(
quot;{Kind} paddles across the pond"); public void Fly() => Console.WriteLine(
quot;{Kind} takes off"); }
Duck paddles across the pond
Duck takes off
True
Max altitude: 1000 m

Interfaces from the standard library

.NET defines many interfaces that unlock built-in features when you implement them:

Interface Implement it to…
IComparable<T> Let Array.Sort, List.Sort and OrderBy sort your objects
IEquatable<T> Provide efficient, type-safe equality
IEnumerable<T> Make your type usable in foreach and LINQ
IDisposable Release resources with a using statement
IFormattable Support format strings like {x:F2}
csharp · try it yourself
using System;
using System.Collections.Generic;

var players = new List<Player>
{
    new Player("Ava", 320),
    new Player("Ben", 410),
    new Player("Cy", 275),
};

players.Sort();   // uses CompareTo
foreach (var p in players)
    Console.WriteLine(
quot;{p.Name}: {p.Score}"); class Player : IComparable<Player> { public string Name { get; } public int Score { get; } public Player(string name, int score) { Name = name; Score = score; } // Highest score first public int CompareTo(Player other) => other.Score.CompareTo(Score); }
Ben: 410
Ava: 320
Cy: 275

Programming to an interface

Code that depends on an interface instead of a concrete class is easier to change and test. Here the Checkout does not care how notifications are sent:

csharp · try it yourself
using System;

var checkout = new Checkout(new ConsoleNotifier());
checkout.Complete("ORD-7");

var silent = new Checkout(new FakeNotifier());
silent.Complete("ORD-8");

interface INotifier { void Send(string message); }

class ConsoleNotifier : INotifier
{
    public void Send(string message) => Console.WriteLine(
quot;[notify] {message}"); } class FakeNotifier : INotifier { public void Send(string message) => Console.WriteLine("(test: message captured, not sent)"); } class Checkout { private readonly INotifier notifier; public Checkout(INotifier notifier) => this.notifier = notifier; public void Complete(string orderId) => notifier.Send(
quot;Order {orderId} confirmed"); }
[notify] Order ORD-7 confirmed
(test: message captured, not sent)

Passing the dependency in through the constructor like this is called dependency injection, and it is everywhere in ASP.NET Core applications.

Default interface methods

Since C# 8 an interface may provide a default body for a member. Implementing types get it for free but can still provide their own. This is mainly used to add members to an existing interface without breaking every class that implements it.

Interface or abstract class?

Interface Abstract class
A type can have Many One
Fields / instance state No Yes
Constructors No Yes
Best for Capabilities shared by unrelated types A family of closely related types sharing code

Test yourself

How many interfaces can a single class implement?

  1. None
  2. One
  3. Two
  4. Any number

Which interface lets List<T>.Sort() sort your objects without extra arguments?

  1. IEnumerable<T>
  2. IComparable<T>
  3. IDisposable
  4. IEquatable<T>

Can you create an object with new IPrintable()?

  1. Yes
  2. No — interfaces cannot be instantiated
  3. Only if it has default methods
  4. Only inside a class