This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

Interface Introduction


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.

Key Points About Interfaces

  1. Declaration: Interfaces are declared using the interface keyword.
  2. Members: Can contain method signatures, properties, events, and indexers.
  3. No Implementation: Interfaces do not provide any implementation; the implementing class or struct must provide the actual code.
  4. Multiple Inheritance: A class can implement multiple interfaces, allowing for a form of multiple inheritance.
  5. Polymorphism: Interfaces enable polymorphism, allowing objects to be treated as instances of their interface rather than their actual class.

Example:

// 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

Interface in C#
Prev Next