C# Interface
An interface in C# is a fully abstract contract. It lists methods and properties that a class must provide, without giving any code for them. Interfaces are a powerful way to achieve abstraction and support multiple inheritance of behaviour.
What Is an Interface?
An interface is like a completely abstract class. It contains only the signatures of methods and properties, never their bodies (in the basic case). A class that uses an interface promises to provide the actual code for every member listed. You can think of an interface as a to-do list that a class agrees to complete.
By convention, interface names in C# start with a capital letter I, for example IAnimal or IShape. This makes them easy to recognize in your code.
Declaring and implementing an interface
interface IAnimal
{
void MakeSound(); // no body, and no access modifier
}
class Cat : IAnimal
{
public void MakeSound()
{
Console.WriteLine("The cat says: meow");
}
}Rules for Interfaces
- You cannot create an object from an interface directly.
- A class that implements an interface must provide a body for every member.
- Interface members do not have an access modifier; they are public automatically.
- A class can implement more than one interface at the same time.
Implementing Multiple Interfaces
C# does not allow a class to inherit from more than one base class. However, a class can implement several interfaces at once by separating them with commas. This is how C# lets a class combine many sets of behaviour.
One class, two interfaces
interface IFirst
{
void MethodOne();
}
interface ISecond
{
void MethodTwo();
}
class DemoClass : IFirst, ISecond
{
public void MethodOne()
{
Console.WriteLine("Method one running");
}
public void MethodTwo()
{
Console.WriteLine("Method two running");
}
}Interfaces are ideal when unrelated classes need to share the same set of abilities. For example, a Bird and an Airplane are very different, but both could implement an IFlyable interface with a Fly method.
Exercise: C# Interface
Can a single C# class implement more than one interface?