Search⌘ K
AI Features

Inheritance and Generics in Interfaces

Understand how C# interfaces support inheritance and generics to create richer contracts. Learn to implement interfaces, use generic interfaces with type safety, and apply interface constraints. Explore real-world uses like dependency injection for flexible and maintainable code.

Classes implement interfaces, but interfaces can also derive from other interfaces. This allows us to build richer contracts by extending existing ones. Unlike classes, interfaces cannot be marked as sealed, meaning there is no way to prevent an interface from being inherited.

When a class implements an interface that inherits from others, it must implement all members declared in the entire inheritance chain.

Interface inheritance
Interface inheritance

Let’s look at the base interface that defines the root behavior.

C# 14.0
namespace Interfaces;
public interface IDownloadable
{
void Download();
}
  • Line 4: We define the Download method signature.

Next, we define a derived interface that extends the base contract.

C# 14.0
namespace Interfaces;
// Inherits from IDownloadable
public interface IShareable : IDownloadable
{
void ShareViaBluetooth();
void ShareViaCloud();
void ShareViaMail();
}
  • Line 4: IShareable inherits from IDownloadable, aggregating its members.

  • Lines 6–8: We add specific sharing methods to this interface.

Now, we create a class that implements the derived interface. Notice that it must satisfy both contracts.

C# 14.0
namespace Interfaces;
// Must implement all members that are declared across the chain of inheritance
public class MultimediaFile : IShareable
{
// Implementation of method from the base interface (IDownloadable)
public void Download()
{
Console.WriteLine("Downloading...");
}
// Implementation of methods from the derived interface (IShareable)
public void ShareViaBluetooth()
{
Console.WriteLine("Sharing via bluetooth...");
}
public void ShareViaCloud()
{
Console.WriteLine("Sharing via cloud...");
}
public void ShareViaMail()
{
Console.WriteLine("Sharing via mail...");
}
}
    ...