Interfaces
An interface
An interface is a contract without state: a list of members a type promises to provide. A class or a struct implements it by naming it after the colon and writing every member, and any code that holds the interface can use the type without knowing which type it is.
var shapes = new List<IArea> { new Circle(2), new Square(3) };
foreach (var shape in shapes)
{
Console.WriteLine($"{shape.Name} {shape.Area:F2}");
}
Console.WriteLine($"count {shapes.Count}");
interface IArea
{
string Name { get; }
double Area { get; }
}
class Circle(double radius) : IArea
{
public string Name => "circle";
public double Area => Math.PI * radius * radius;
}
class Square(double side) : IArea
{
public string Name => "square";
public double Area => side * side;
}
dotnet run
circle 12.57
square 9.00
count 2
The list is a List<IArea>, so it can hold any implementation, now or later. The two classes have nothing in common except the contract, which is the difference from the abstract class of the earlier lesson: there is no shared code and no base state, so an interface can sit beside a completely unrelated base class.
Several interfaces and an explicit one
A class may implement as many interfaces as it likes. When two interfaces both declare a member with the same name, or when a member exists only for one interface, it is written explicitly as void ISave.Save() and reached through the interface:
var report = new Report();
report.Print();
((ISave)report).Save();
Console.WriteLine("done");
interface IPrint
{
void Print();
}
interface ISave
{
void Save();
}
class Report : IPrint, ISave
{
public void Print() => Console.WriteLine("print");
void ISave.Save() => Console.WriteLine("save");
}
dotnet run
print
save
done
An explicit implementation has no access modifier and is not a member of the class surface: report.Save() does not compile, and the cast is the way in. That is how a class implements two interfaces that both declare Save with different meanings, and how it keeps a member out of the public API while still satisfying the contract.
An interface as a parameter
The usual use of an interface is a method that takes one, so the caller decides which implementation runs. A struct may implement an interface too, and a struct passed as the interface is boxed:
Print(new Circle(1.5));
Print(new Square(2));
Console.WriteLine("both printed");
static void Print(IArea shape) => Console.WriteLine($"{shape.Name} {shape.Area:F2}");
interface IArea
{
string Name { get; }
double Area { get; }
}
readonly struct Square(double side) : IArea
{
public string Name => "square";
public double Area => side * side;
}
class Circle(double radius) : IArea
{
public string Name => "circle";
public double Area => Math.PI * radius * radius;
}
dotnet run
circle 7.07
square 4.00
both printed
The class went to the method as a reference and the struct was copied into a box, because an interface variable holds an object reference. A generic method with a constraint avoids the box for a struct, and the lesson on generics and the one on boxing measure both paths.
An interface against an abstract class
- An interface declares behaviour and holds no instance state: no fields, no constructor, no protected helper.
- An abstract class may carry shared code, fields and a constructor, and a class has only one base class to give it.
- A type may implement many interfaces and derive from one class, so the usual design is an interface for the contract and a base class for the shared part.
- Both are used as the type of a variable and both dispatch on the runtime implementation; the difference is what else they can hold.
Since C# 8 an interface may also carry a default implementation of a member, which blurs the line a little. The next lesson is about exactly that, and about the static abstract members that came with C# 11.
Exercises
- Add a Triangle to the first program and put it in the same list.
- Give Report a second interface with a Save of its own and implement both explicitly.
- Write a generic Print<T>(T shape) where T : IArea and pass a struct to it. Does the box disappear?
- Make IArea an abstract class with a concrete Describe method and compare the two designs.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What may an interface contain?
Answer
Member declarations, and since C# 8 default implementations
An interface has no instance state; default members came later and still hold none.
-
How many interfaces may one class implement?
Answer
Any number
A class has one base class and any number of interfaces.
-
What does this program print?
var list = new List<IA> { new B() }; Console.WriteLine(list[0].Name); interface IA { string Name { get; } } class B : IA { public string Name => "b"; }Answer
b
The interface member is dispatched to the implementation in B.
-
What does an explicit interface implementation change?
Answer
The member is reachable only through the interface
It is not part of the class surface, so a cast to the interface is needed.
-
What happens to a struct passed as an interface parameter?
Answer
It is boxed into an object
An interface variable holds an object reference, so the value has to be boxed.
-
What does this program print?
IPrint p = new R(); p.Print(); interface IPrint { void Print(); } class R : IPrint { public void Print() => Console.WriteLine("r"); }Answer
r
The interface call reaches the implementation the object provides.
-
Which can an abstract class do that an interface cannot?
Answer
Hold instance fields and a constructor
State and construction belong to a class; an interface is a pure contract.
-
What does a class need to do to satisfy an interface?
Answer
Implement every member with a matching signature
The compiler checks each member and reports CS0535 for any that is missing.
-
Why is a method parameter typed as an interface flexible?
Answer
Any implementation, existing or future, can be passed
The caller decides the implementation, so the method needs no change for a new one.
-
Which naming convention do interfaces follow in C#?
Answer
A capital I, as in IArea
The I prefix is a .NET convention that makes an interface visible at the call site.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev