← 講座に戻る: C# from scratch

Interfaces, polymorphism and composition

動画は近日公開

Inheritance has a limit: a class can only have one base class. And often what we want to express is not "is a kind of", but "knows how to". A duck, a plane and a drone can fly without having anything else in common. For this C# has interfaces: a contract that lists members without implementing them. Any class that declares it fulfills the interface is required to write those members, and whoever uses the interface can trust that they exist, regardless of which concrete class it is.

Declaring and implementing an interface

By convention, the name of an interface starts with a capital I: IFlyable, IComparable. Its members carry no modifier and no body. A class implements one or several interfaces separated by commas after the colon. A variable can be declared with the interface type and hold any object that implements it; this way you write code that works with anything, now and in the future. .NET provides many useful interfaces: IComparable for sorting, IEnumerable to loop with foreach and IDisposable to release resources.

csharp
List<INotifier> notifiers = [new EmailNotifier("ana@example.com"), new SmsNotifier("555-0101")];

foreach (INotifier n in notifiers)
{
    n.Send("Your order has shipped");
}
// Email to ana@example.com: Your order has shipped
// SMS to 555-0101: Your order has shipped

interface INotifier
{
    void Send(string message);
}

class EmailNotifier(string address) : INotifier
{
    public void Send(string message) => Console.WriteLine($"Email to {address}: {message}");
}

class SmsNotifier(string phone) : INotifier
{
    public void Send(string message) => Console.WriteLine($"SMS to {phone}: {message}");
}

.NET interfaces and multiple contracts

A class can fulfill several contracts at once, something inheritance does not allow. By implementing IComparable<T>, your type gains the ability to be sorted with Sort without writing anything else. When several classes share a behavior, the interface lets you replace one with another without changing the rest of the program; this is called decoupling. For example, a service that saves data can ask for an IStorage and it does not matter whether underneath it is a file, a database or an in-memory list. That idea is the basis of automated tests and large applications.

csharp
var people = new List<Person>
{
    new Person("Luis", 31),
    new Person("Ana", 25),
    new Person("Marta", 28),
};
people.Sort();                       // uses IComparable<Person>
foreach (var p in people) Console.WriteLine($"{p.Name} {p.Age}");
// Ana 25, Marta 28, Luis 31

IStorage storage = new MemoryStorage();
var service = new ReportService(storage);   // composition
service.Save("report-1");
Console.WriteLine(storage.Count());          // 1

class Person(string name, int age) : IComparable<Person>
{
    public string Name { get; } = name;
    public int Age { get; } = age;
    public int CompareTo(Person? other) => other is null ? 1 : Age.CompareTo(other.Age);
}

interface IStorage
{
    void Add(string item);
    int Count();
}

class MemoryStorage : IStorage
{
    private readonly List<string> _items = [];
    public void Add(string item) => _items.Add(item);
    public int Count() => _items.Count;
}

class ReportService(IStorage storage)
{
    public void Save(string name) => storage.Add(name);
}

理解度チェック

問題 1 / 2

How many interfaces can a class implement?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →