CHASH Tutorial



C# INTERFACE


C# Interface

An interface in C# defines a contract that classes can implement. It only contains method declarations (no implementation). A class that implements an interface must provide an implementation for all its members.

💡 Think of it like this:
An interface is a "what to do" guide — the "how to do" part is left to the class that implements it.

Declaring and Using an Interface

interface IVehicle
{
    void Start();
    void Stop();
}

class Car : IVehicle
{
    public void Start()
    {
        Console.WriteLine("Car started.");
    }

    public void Stop()
    {
        Console.WriteLine("Car stopped.");
    }
}

class Program
{
    static void Main()
    {
        IVehicle myCar = new Car();
        myCar.Start();   // Output: Car started.
        myCar.Stop();    // Output: Car stopped.
    }
}
  
Output:
Car started.
Car stopped.

Why Use Interfaces?

  • Supports multiple inheritance (classes can't inherit multiple classes, but can implement multiple interfaces)
  • Enables polymorphism
  • Improves code flexibility and testability
  • Ensures a contract for classes (they must follow specific rules)

Multiple Interfaces

interface IAnimal
{
    void Eat();
}

interface IPet
{
    void Play();
}

class Dog : IAnimal, IPet
{
    public void Eat()
    {
        Console.WriteLine("Dog is eating.");
    }

    public void Play()
    {
        Console.WriteLine("Dog is playing.");
    }
}
  
🧠 A class can implement any number of interfaces.

Interface vs Abstract Class

Feature Interface Abstract Class
Implementation Only declarations Can have both declarations and definitions
Multiple inheritance Allowed Not allowed
Access modifiers Not allowed Allowed
📝 Tip: Use interfaces when you need to define a contract for unrelated classes.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review