Lesson 14 of 15

Interfaces

Interfaces

An interface defines a contract — a set of methods and properties that implementing classes must provide:

interface ILogger {
    void Log(string message);
    string Prefix { get; }
}

class ConsoleLogger : ILogger {
    public string Prefix => "[INFO]";
    public void Log(string message) => Console.WriteLine($"{Prefix} {message}");
}

ILogger logger = new ConsoleLogger();
logger.Log("Application started"); // [INFO] Application started

Multiple Interfaces

A class can implement multiple interfaces (unlike inheritance, which allows only one base class):

interface ISaveable { void Save(); }
interface ILoadable { void Load(); }

class Document : ISaveable, ILoadable {
    public void Save() => Console.WriteLine("Saving...");
    public void Load() => Console.WriteLine("Loading...");
}

Your Task

Define an interface IGreeter with:

  • string Greet(string name) method

Then create two implementations:

  • FormalGreeter — returns "Good day, {name}."
  • CasualGreeter — returns "Hey, {name}!"
WasmSharp (.NET) loading...
Loading...
Click "Run" to execute your code.