Sure! In C#, an interface is a blueprint for a class. It defines a set of methods and properties that a class must implement if it implements that interface. Think of an interface as a contract that a class agrees to fulfill. Interfaces provide a way to achieve abstraction and polymorphism in C#.
Here's a simple explanation with an example:
Suppose we want to create an interface called IAnimal
that defines a method MakeSound()
, and then we implement this interface in two different classes: Dog
and Cat
.
Example
using System;
// Interface defining the blueprint for animals
interface IAnimal
{
void MakeSound(); // Method signature for making sound
}
// Class implementing the IAnimal interface
class Dog : IAnimal
{
public void MakeSound()
{
Console.WriteLine("Dog barks");
}
}
// Class implementing the IAnimal interface
class Cat : IAnimal
{
public void MakeSound()
{
Console.WriteLine("Cat meows");
}
}
class Program
{
static void Main(string[] args)
{
IAnimal dog = new Dog(); // Creating a Dog object using IAnimal interface
IAnimal cat = new Cat(); // Creating a Cat object using IAnimal interface
dog.MakeSound(); // Calls the MakeSound() method of Dog class
cat.MakeSound(); // Calls the MakeSound() method of Cat class
}
}
In this example:
IAnimal
with a method MakeSound()
. This method represents a common behavior shared by different animals.Dog
and Cat
, both of which implement the IAnimal
interface. This means that any class that implements IAnimal
must provide an implementation for the MakeSound()
method.Main
method, we create instances of Dog
and Cat
using the interface type IAnimal
. This allows us to treat different animals uniformly, without concerning ourselves with their specific implementations.MakeSound()
method on each animal object, the appropriate implementation for that animal is invoked, demonstrating polymorphism through the interface.Interfaces are useful for defining contracts that classes must adhere to, enabling code to be more flexible, modular, and easy to maintain. They also facilitate code reuse and promote loosely coupled designs.