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.
We'll cover the following...
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.
Let’s look at the base interface that defines the root behavior.
Line 4: We define the
Downloadmethod signature.
Next, we define a derived interface that extends the base contract.
Line 4:
IShareableinherits fromIDownloadable, 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.