What Is an Interface in C#?
- An interface in C# is a fully unimplemented class used for declaring a set of operations or methods that an object must provide.
- It serves as a pure abstract class, allowing us to define only abstract methods (methods without a body).
- Interfaces are used to achieve multiple inheritances, which classes cannot achieve directly.
- They also ensure full abstraction because interface methods cannot have a method body.
- In C#, an interface is a fundamental concept defining a contract or a set of rules that a class must adhere to.
- It specifies a list of methods, properties, events, or indexers that a class implementing the interface must provide.
- Interfaces allow you to define a common set of functionality that multiple classes can share, promoting code reusability and ensuring a consistent structure for related classes.
Differences Between Concrete Class, Abstract Class, and Interface in C#:
- Concrete Class:
- Contains only non-abstract methods (methods with a method body).
- Abstract Class:
- Contains both non-abstract methods and abstract methods (methods without a method body).
- Interface:
- Contains only abstract methods (methods without a method body).
- Concrete Class:
Real-World Example: Library Management System
Imagine building a Library Management System where you need to handle different types of library items (books, DVDs, etc.).
We can define an interface called
ILibraryItem
to specify common behavior for all library items:interface ILibraryItem { string Title { get; set; } void CheckOut(string borrower); void Return(); }
Now, let’s implement this interface for specific library items:
Book:
class Book : ILibraryItem { public string Title { get; set; } public void CheckOut(string borrower) { // Logic for checking out a book } public void Return() { // Logic for returning a book } }
DVD:
class DVD : ILibraryItem { public string Title { get; set; } public void CheckOut(string borrower) { // Logic for checking out a DVD } public void Return() { // Logic for returning a DVD } }
By using the
ILibraryItem
interface, we ensure that all library items adhere to the same contract, allowing consistent handling across different types of items.Interfaces promote code reusability, maintainability, and a consistent structure for related classes.
Remember, interfaces provide a powerful way to define contracts and encourage good design practices in your C# code!