Default interface methods
Learn backward compatibility with default interface methods.
Default interface methods
From C# 8 onwards interface methods can have a body. These are called default interface methods. Declaration: void Write(string message) { Console.WriteLine(message); }.
When a class implements this interface, it does not have to override the default method; the body from the interface is used. This preserves backward compatibility when adding methods to existing interfaces. A default method can only be called through an interface-typed variable, not a class-typed one.
Calling default methods
If a class does not override the default method, the call uses the interface's body. The call must be made through the interface type: IWriter w = new ConsoleWriter(); w.Write("Hello");.
If the class writes its own body, that one is used. Default methods suit helper methods and backward compatibility. Providing a default body when adding a new method doesn't break existing implementing classes.
Exercise Default writer
Add a default body to IWriter's void Write(string message) method: Console.WriteLine(message);. In Main, create IWriter w = new ConsoleWriter(); and call w.Write("Hello").
Show example solution
Add `void Write(string message) { Console.WriteLine(message); }` to IWriter. In Main write `IWriter w = new ConsoleWriter(); w.Write("Hello");`.
Example solution:
using System;
interface IWriter
{
void Write(string message)
{
Console.WriteLine(message);
}
}
class ConsoleWriter : IWriter
{
}
class Program
{
static void Main()
{
IWriter w = new ConsoleWriter();
w.Write("Hello");
}
}
Test yourself
-
Which statement about default interface methods is correct?
- Default methods must be static.
- Default methods must be overridden in the implementing class.
- Default methods exist only in C# 7.
- Default methods have a body and provide backward compatibility.
Show answer
Default methods have a body and provide backward compatibility. — Correct. Default methods have a body and make it safe to add methods to existing interfaces.
-
Match: default method parts
- body
- in curly braces
- no override
- default body is used
- interface type
- call route
- backward compatibility
- new method added safely
-
Fill in the blank: default method body
interface IWriter { void Write(string message) ____ Console.WriteLine(message); } }Show answer
interface IWriter { void Write(string message) { Console.WriteLine(message); } }