In this article we are going to discuss Interface in C#. There are many blogs, articles are available on the internet regarding Interface but in this particular article I will try to explain to you with as much as simple.
Interface Introduction
In C#, an interface is a contract that defines a set of methods, properties, events, or indexers without implementing them. Interfaces specify what a class must do but not how it does it. A class or struct that implements an interface must implement all its members.
// Define an interface
public interface IAnimal
{
// Interface members
void Eat();
void Sleep();
}
// Implement the interface in a class
public class Dog : IAnimal
{
public void Eat()
{
Console.WriteLine("Dog is eating.");
}
public void Sleep()
{
Console.WriteLine("Dog is sleeping.");
}
}
// Implement the interface in another class
public class Program
{
public static void Main()
{
IAnimal dog = new Dog();
dog.Eat(); // Output: Dog is eating.
dog.Sleep(); // Output: Dog is sleeping.
Console.ReadKey();
}
}
Output