0
0
CsharpConceptBeginner · 3 min read

What is Interface in C#: Definition and Usage

In C#, an interface is a contract that defines a set of methods and properties without implementing them. Classes or structs that implement the interface must provide the actual code for these members, ensuring consistent behavior across different types.
⚙️

How It Works

Think of an interface as a promise or a list of rules that a class agrees to follow. It only says what methods or properties should exist, but not how they work. This is like a remote control that guarantees buttons for volume and power, but each TV brand decides how those buttons actually work.

When a class implements an interface, it must write the code for all the methods and properties the interface lists. This helps different classes share the same set of actions, making it easier to use them interchangeably in your program.

💻

Example

This example shows an interface IVehicle with a method Drive. Two classes, Car and Bike, implement this interface with their own version of Drive.

csharp
using System;

interface IVehicle
{
    void Drive();
}

class Car : IVehicle
{
    public void Drive()
    {
        Console.WriteLine("Car is driving smoothly.");
    }
}

class Bike : IVehicle
{
    public void Drive()
    {
        Console.WriteLine("Bike is driving fast.");
    }
}

class Program
{
    static void Main()
    {
        IVehicle myCar = new Car();
        IVehicle myBike = new Bike();

        myCar.Drive();
        myBike.Drive();
    }
}
Output
Car is driving smoothly. Bike is driving fast.
🎯

When to Use

Use interfaces when you want different classes to share the same set of actions but implement them differently. This is helpful when you want to write flexible code that can work with many types without knowing their details.

For example, in a game, you might have an interface IEnemy that all enemy types implement. Each enemy can move or attack differently, but your game code can treat them all as IEnemy to simplify logic.

Key Points

  • An interface defines a contract with methods and properties but no code.
  • Classes or structs that implement an interface must provide the code.
  • Interfaces help create flexible and reusable code by allowing different types to be used interchangeably.
  • C# supports multiple interfaces on a single class, enabling rich behavior combinations.

Key Takeaways

An interface in C# defines a set of methods and properties without implementation.
Classes implementing an interface must provide code for all its members.
Interfaces enable flexible code by allowing different classes to be used interchangeably.
Use interfaces to design clear contracts and improve code maintainability.