What Is an Interface in C#?
An interface in C# is a contract that defines a set of methods, properties, events, or indexers—without providing any implementation. A class or struct that implements an interface must provide the implementation for all its members.
Key Features of Interfaces
- Cannot contain implementation (except default interface methods in newer C# versions).
- A class can implement multiple interfaces (supports multiple inheritance).
- Defines “what” a class should do, not “how” it should do it.
- Members are public by default.
Example in C#
interface IAnimal
{
void MakeSound(); // method without implementation
void Sleep(); // another method
}
class Dog : IAnimal
{
public void MakeSound()
{
Console.WriteLine("Bark!");
}
public void Sleep()
{
Console.WriteLine("Sleeping...");
}
}
Here, IAnimal is an interface that declares two methods.
The Dog class implements this interface and provides the actual
method bodies.
No comments:
Post a Comment