Search⌘ K

Inheritance and Generics in Interfaces

Explore how interfaces in C# inherit from other interfaces and how to implement all inherited members. Understand the creation and use of generic interfaces, including implementing them with concrete types. Learn to constrain generic type parameters using interfaces to enforce type safety in your applications.

Inheritance in interfaces

Classes implement interfaces, but interfaces can derive from other interfaces. Everything we learned about inheritance is applicable to interfaces, except that iInterfaces can’t be marked as sealed.

There’s no way to prevent interfaces from inheriting from other interfaces. Also, when we implement an interface, we must implement all members that the interface inherited from its base interfaces:

Let’s see it in code:

C#
using System;
namespace Interfaces
{
// Must implement all members that are declared
// across the chain of inheritance
public class MultimediaFile : IShareable
{
// Method declared in IDownloadable
public void Download()
{
Console.WriteLine("Downloading...");
}
public void ShareViaBluetooth()
{
Console.WriteLine("Sharing via bluetooth...");
}
public void ShareViaCloud()
{
Console.WriteLine("Sharing via cloud...");
}
public void ShareViaMail()
{
Console.WriteLine("Sharing via mail...");
}
}
}

In the code above, ...