0Pricing
C# Academy · Lesson

Interfaces (intro) & multiple interface implementation

Define interfaces as contracts, implement multiple interfaces in one class, use interface-based polymorphism, and learn explicit interface implementation basics.

Interfaces overview

Goal: Program to interfaces for flexible code.

  • Interfaces declare what, not how
  • Implement multiple interfaces
  • Pass interfaces to functions
  • Explicit implementation to resolve name clashes

Implementing multiple interfaces

Interfaces define a contract. One class can implement multiple interfaces to express different roles.

using System;

public interface IPlayable
{
  void Play();
}

public interface IHasDuration
{
  int DurationSeconds { get; }
}

public class Song : IPlayable, IHasDuration
{
  private readonly string _title;
  private readonly int _seconds;

  public Song(string title, int seconds)
  {
    _title = title;
    _seconds = seconds;
  }

  public int DurationSeconds { get { return _seconds; } }

  public void Play()
  {
    Console.WriteLine("Playing " + _title + " (" + _seconds + "s)");
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    Song s = new Song("Hello", 5);
    s.Play();
    Console.WriteLine("Duration = " + s.DurationSeconds);
  }
}

All lessons in this course

  1. virtual/override/sealed; abstract classes
  2. Interfaces (intro) & multiple interface implementation
  3. Polymorphism & dynamic dispatch
← Back to C# Academy