In C#, an interface is a contract that defines a set of methods, properties, events, or indexers that a class or struct must implement. Interfaces are used to achieve abstraction and polymorphism in object-oriented programming. They allow different classes to implement the same set of methods, promoting a consistent API across different types.
Key Features of Interfaces
- No Implementation: Interfaces cannot contain any implementation (i.e., no method bodies). They only define the signatures.
- Multiple Inheritance: A class can implement multiple interfaces, allowing for a form of multiple inheritance.
- Polymorphism: Interfaces allow for polymorphism, meaning that different classes can be treated as instances of the same interface type.
Defining an Interface
Here’s how you can define an interface in C#:
csharp1public interface IAnimal 2{ 3 void Speak(); // Method signature 4 string Name { get; set; } // Property signature 5}
Implementing an Interface
A class can implement an interface using the :
syntax. Here’s an example:
csharp1public class Dog : IAnimal 2{ 3 public string Name { get; set; } 4 5 public Dog(string name) 6 { 7 Name = name; 8 } 9 10 public void Speak() 11 { 12 Console.WriteLine($"{Name} says Woof!"); 13 } 14} 15 16public class Cat : IAnimal 17{ 18 public string Name { get; set; } 19 20 public Cat(string name) 21 { 22 Name = name; 23 } 24 25 public void Speak() 26 { 27 Console.WriteLine($"{Name} says Meow!"); 28 } 29}
Using the Interface
You can create instances of the classes that implement the interface and call their methods:
csharp1class Program 2{ 3 static void Main(string[] args) 4 { 5 IAnimal dog = new Dog("Buddy"); 6 IAnimal cat = new Cat("Whiskers"); 7 8 dog.Speak(); // Output: Buddy says Woof! 9 cat.Speak(); // Output: Whiskers says Meow! 10 } 11}
Interface with Multiple Implementations
You can implement the same interface in different classes:
csharp1public class Bird : IAnimal 2{ 3 public string Name { get; set; } 4 5 public Bird(string name) 6 { 7 Name = name; 8 } 9 10 public void Speak() 11 { 12 Console.WriteLine($"{Name} says Tweet!"); 13 } 14}
Example with Multiple Interfaces
You can also implement multiple interfaces in a single class:
csharp1public interface IMovable 2{ 3 void Move(); 4} 5 6public class Car : IAnimal, IMovable 7{ 8 public string Name { get; set; } 9 10 public Car(string name) 11 { 12 Name = name; 13 } 14 15 public void Speak() 16 { 17 Console.WriteLine($"{Name} goes vroom!"); 18 } 19 20 public void Move() 21 { 22 Console.WriteLine($"{Name} is moving!"); 23 } 24}
Using the Class with Multiple Interfaces
csharp1class Program 2{ 3 static void Main(string[] args) 4 { 5 IAnimal myDog = new Dog("Buddy"); 6 IMovable myCar = new Car("Tesla"); 7 8 myDog.Speak(); // Output: Buddy says Woof! 9 myCar.Move(); // Output: Tesla is moving! 10 } 11}
Default Interface Methods (C# 8.0 and later)
Starting from C# 8.0, interfaces can contain default implementations for methods. This allows you to add new methods to an interface without breaking existing implementations.
csharp1public interface IAnimal 2{ 3 void Speak(); 4 5 // Default implementation 6 void Eat() 7 { 8 Console.WriteLine("Eating..."); 9 } 10} 11 12public class Dog : IAnimal 13{ 14 public string Name { get; set; } 15 16 public Dog(string name) 17 { 18 Name = name; 19 } 20 21 public void Speak() 22 { 23 Console.WriteLine($"{Name} says Woof!"); 24 } 25}
Using the Default Method
csharp1class Program 2{ 3 static void Main(string[] args) 4 { 5 IAnimal dog = new Dog("Buddy"); 6 dog.Speak(); // Output: Buddy says Woof! 7 dog.Eat(); // Output: Eating... 8 } 9}
Summary
- Interfaces define a contract that classes must adhere to, promoting a consistent API.
- A class can implement multiple interfaces, allowing for flexible designs.
- Interfaces enable polymorphism, allowing you to treat different classes as instances of the same interface type.
- With C# 8.0 and later, interfaces can include default implementations, making it easier to evolve interfaces without breaking existing implementations.
Reasons to Use Interfaces
Abstraction:
- Interfaces define a contract without specifying implementation details, allowing for a clear separation between the "what" and the "how."
Polymorphism:
- Interfaces enable polymorphic behavior, allowing objects of different classes to be treated as instances of a common interface type.
Multiple Inheritance:
- A class can implement multiple interfaces, allowing for a form of multiple inheritance that promotes code reuse and flexibility.
Decoupling Code:
- Interfaces promote loose coupling between components, making it easier to change implementations without affecting dependent code.
Easier Testing and Mocking:
- Interfaces facilitate unit testing by allowing the creation of mock objects that simulate behavior without relying on concrete implementations.
Consistency and Standardization:
- Interfaces enforce a consistent API across different implementations, making code easier to understand and use.
Future-proofing Code:
- Interfaces can evolve with default implementations, allowing new methods to be added without breaking existing implementations.
Improved Maintainability:
- Code that uses interfaces is generally easier to maintain, as changes to one implementation do not necessitate changes to consumers of the interface.
Enhanced Collaboration:
- In team environments, interfaces help standardize interactions between different parts of the application, enabling better collaboration among developers.
Clearer Design:
- Using interfaces can lead to a clearer architectural design, making it easier to visualize relationships between components.