A base class says what something is. An interface only says what it can do: a list of members with no stored data. Any class or record can promise to provide them, whatever else it is, and a type can implement as many interfaces as it likes. Interface names start with I by convention.
A small contract
INotifier has one method. Code that takes an INotifier works with every implementation, including ones written later.
Remind(new ScreenNotifier(), "Stretch");
Remind(new QuietNotifier(), "Stretch");
static void Remind(INotifier notifier, string message)
{
notifier.Send(message);
Console.WriteLine("Reminder handled");
}
interface INotifier
{
void Send(string message);
}
class ScreenNotifier : INotifier
{
public void Send(string message)
{
Console.WriteLine($"* {message} *");
}
}
class QuietNotifier : INotifier
{
public void Send(string message)
{
}
}Check your prediction
* Stretch *
Reminder handled
Reminder handledRemind has no idea which class it was given, and it doesn't need to know. You'll use this on Day 6 to replace a real file with a fake during tests.
Several interfaces at once
A class has one base class at most, but it can implement many interfaces. The caller sees only the part it asked for: through an IReader variable, Write isn't available even though the object has it.
var box = new MemoryBox();
IWriter writer = box;
IReader reader = box;
writer.Write("hello");
Console.WriteLine(reader.Read());
interface IReader
{
string Read();
}
interface IWriter
{
void Write(string text);
}
class MemoryBox : IReader, IWriter
{
private string content = "";
public string Read() => content;
public void Write(string text)
{
content = text;
}
}Check your prediction
helloSmall interfaces are easier to implement and to fake. Prefer several narrow ones to one that does everything.
Interfaces you already use
The library is built on interfaces. IEnumerable<T> means "can be looped over", and it's why foreach accepts arrays, lists and sets alike. IComparable<T> means "knows how it orders against another of its type", and Sort uses it. Implement it, and your type sorts. The record below is named Version2 only so it can't clash with the library's own System.Version.
#nullable enable
var versions = new List<Version2> { new(1, 10), new(1, 2), new(0, 9) };
versions.Sort();
foreach (Version2 version in versions)
{
Console.WriteLine($"{version.Major}.{version.Minor}");
}
record Version2(int Major, int Minor) : IComparable<Version2>
{
public int CompareTo(Version2? other)
{
if (other is null)
{
return 1;
}
int major = Major.CompareTo(other.Major);
return major != 0 ? major : Minor.CompareTo(other.Minor);
}
}Check your prediction
0.9
1.2
1.10Version2? says that other may be null, and #nullable enable switches that notation on. Day 4 covers it. CompareTo returns a negative number, zero or a positive number. Delegating to int.CompareTo avoids the classic bug of subtracting two values, which can overflow. As text, 1.10 would sort before 1.2, so comparing numbers matters here.
Interface or base class?
| Choose | When |
|---|---|
| An interface | Unrelated types share a capability, or you want to swap implementations |
| An abstract class | Closely related types share real code and data |
When you're unsure, start with an interface. You can always add a shared base class behind it later.
Fix it: The method that doesn't count
LoudNotifier has a Send method with the right name and parameters, yet the compiler refuses it. Run it and read the error.
INotifier notifier = new LoudNotifier();
notifier.Send("Stretch");
interface INotifier
{
void Send(string message);
}
class LoudNotifier : INotifier
{
void Send(string message)
{
Console.WriteLine(message.ToUpper());
}
}Check your prediction
error CS0737
cannot implement an interface member because it is not publicA class member with no access modifier is private, and a private method can't be the one that callers reach through INotifier. So, as far as the interface is concerned, LoudNotifier has no Send at all. Fix it.
Fix it
Make the method public:
INotifier notifier = new LoudNotifier();
notifier.Send("Stretch");
interface INotifier
{
void Send(string message);
}
class LoudNotifier : INotifier
{
public void Send(string message)
{
Console.WriteLine(message.ToUpper());
}
}STRETCHInterface members are public by default, so it's easy to forget that the class's own members aren't. When the compiler says a class doesn't implement a member you can see, check its access modifier first.
Your turn
Interchangeable discounts
Define IDiscount with decimal Apply(decimal price). Write NoDiscount, PercentOff (for example 10 percent) and AmountOff (for example 5, never going below 0). Write a static method Total(List<decimal> prices, IDiscount discount) that adds up the discounted prices. Print totals for prices 20 and 3 with each of the three discounts: none, 10 percent and 5 off.
When it works, it prints:
23
20.7
15var prices = new List<decimal> { 20m, 3m };
Console.WriteLine(prices.Count);Hint 1: the idea
Total loops over the prices and calls Apply on each. It should never check which discount it was given.
Hint 2: a first step
Write the interface and NoDiscount, then get Total working with it. Use Math.Max for the rule about not going below 0.
Show one solution
var prices = new List<decimal> { 20m, 3m };
Console.WriteLine(Total(prices, new NoDiscount()));
Console.WriteLine(Total(prices, new PercentOff(10m)));
Console.WriteLine(Total(prices, new AmountOff(5m)));
static decimal Total(List<decimal> prices, IDiscount discount)
{
decimal total = 0m;
foreach (decimal price in prices)
{
total += discount.Apply(price);
}
return total;
}
interface IDiscount
{
decimal Apply(decimal price);
}
class NoDiscount : IDiscount
{
public decimal Apply(decimal price) => price;
}
record PercentOff(decimal Percent) : IDiscount
{
public decimal Apply(decimal price) => price - price * Percent / 100m;
}
record AmountOff(decimal Amount) : IDiscount
{
public decimal Apply(decimal price) => Math.Max(0m, price - Amount);
}23
20.7
15Total knows only IDiscount, so a new kind of discount never changes it. NoDiscount exists so that "no discount" is an object like the others, rather than a null that Total would have to check for. Math.Max(0m, …) in AmountOff stops a cheap item going below zero, which is why the last total is 15: the 20 becomes 15, and the 3 becomes 0 rather than -2.
Completion is saved in this browser only. It does not measure mastery.