Glossary / Interfaces

Interfaces

An interface defines a contract of members and capabilities that classes, structs, and other types can implement. A type can implement multiple interfaces, enabling polymorphism across unrelated types without sharing a base-class hierarchy.

Members and implementation

Interfaces can declare methods, properties, events, indexers, static abstract members, and—since C# 8—default implementations for eligible instance members. Default interface members help evolve contracts but are not ordinary inherited class members in every lookup scenario; implementations can override or explicitly implement them. Interface members are public contracts unless default/private helper rules apply.

public interface IClock { DateTimeOffset UtcNow { get; } }
public sealed class SystemClock : IClock
{
    public DateTimeOffset UtcNow => DateTimeOffset.UtcNow;
}

Explicit implementation (for example, DateTimeOffset IClock.UtcNow => ...) hides an implementation from the concrete type's public member lookup and disambiguates collisions. Interface dispatch through a value-type instance can box, while generic constraints may avoid boxing.

API and design use

Interfaces are useful for substitutable services, test seams, and capabilities. Avoid creating an interface for every class without a consumer need; abstractions have versioning costs. Interface segregation favors small role-oriented contracts. Changing an interface can break implementers, though default members can mitigate some additive changes; runtime and language support must be considered.

Interview questions

  1. Why interfaces? Shared capability contracts and polymorphism across otherwise unrelated types.
  2. Can a type implement multiple interfaces? Yes.
  3. What are default interface methods? Interface-provided implementations that can evolve certain contracts, introduced in C# 8.
  4. What is explicit implementation for? Hiding members from the concrete API or resolving member-name collisions.
  5. When avoid an interface? When it adds indirection without multiple implementations, a test seam, or a meaningful contract.

References