C# Interface
In C#, an interface is a blueprint for a set of methods, properties, and events. An interface defines a contract that a class must implement, and provides the signatures for those methods, properties, and events. In this tutorial, we'll discuss how to define and use interfaces in C#.
Syntax
The syntax for defining an interface in C# is as follows:
interface IMyInterface {
// method declarations
// property declarations
// event declarations
}
Any class that implements this interface must provide implementations for the methods, properties, and events defined in the interface.
Example
Let's say we want to define an interface called "IAnimal" that defines methods for speaking and walking. Here's how we can implement it:
interface IAnimal {
void Speak();
void Walk();
}
Now, we can implement this interface in our classes:
class Cat : IAnimal {
public void Speak() {
Console.WriteLine("Meow");
}
public void Walk() {
Console.WriteLine("Cat is walking");
}
}
class Dog : IAnimal {
public void Speak() {
Console.WriteLine("Woof");
}
public void Walk() {
Console.WriteLine("Dog is walking");
}
}
Finally, we can use these classes and their implementations of the interface in our code:
Cat myCat = new Cat();
myCat.Speak();
myCat.Walk();
Dog myDog = new Dog();
myDog.Speak();
myDog.Walk();
Output
When we run the example code above, the output will be:
Meow
Cat is walking
Woof
Dog is walking
This is because the Cat and Dog classes provide implementations for the methods defined in the IAnimal interface.
Explanation
In the example above, we defined an interface called "IAnimal" that defines methods for speaking and walking. We then implemented this interface in our Cat and Dog classes, providing implementations for the methods. Finally, we used these classes and their implementations of the interface in our code to call the Speak and Walk methods.
Use
Interfaces are useful for defining contracts that classes must implement, providing a way to ensure that classes have certain behavior and functionality. You can use interfaces to create modular and reusable code, as well as to facilitate polymorphism and dependency injection.
Important Points
- Interfaces only define a contract, and do not contain any implementation code.
- A class can implement multiple interfaces in C#.
- Interfaces can inherit from other interfaces.
- Interfaces can be implemented explicitly or implicitly.
Summary
In this tutorial, we discussed how to define and use interfaces in C#. We covered the syntax, example, output, explanation, use, and important points of interfaces in C#. With this knowledge, you can now use interfaces in your C# code to define contracts that classes must implement, providing a way to ensure that they have certain behavior and functionality.