0
0
CsharpHow-ToBeginner · 3 min read

How to Implement Interface in C#: Syntax and Example

In C#, you implement an interface by creating a class that uses the : symbol followed by the interface name and then providing definitions for all its members. Use the interface keyword to define the interface and implement its methods and properties in the class.
📐

Syntax

An interface in C# is defined using the interface keyword. To implement it, a class uses the : symbol followed by the interface name. The class must then provide concrete implementations for all interface members.

  • interface IExample: Declares an interface named IExample.
  • class MyClass : IExample: Declares a class MyClass that implements IExample.
  • All methods and properties declared in the interface must be implemented in the class.
csharp
interface IExample
{
    void DoWork();
    int Value { get; set; }
}

class MyClass : IExample
{
    public int Value { get; set; }

    public void DoWork()
    {
        // Implementation code here
    }
}
💻

Example

This example shows how to define an interface IVehicle and implement it in a class Car. The class provides the required method and property implementations.

csharp
using System;

interface IVehicle
{
    void Drive();
    int Speed { get; set; }
}

class Car : IVehicle
{
    public int Speed { get; set; }

    public void Drive()
    {
        Console.WriteLine($"Driving at {Speed} km/h");
    }
}

class Program
{
    static void Main()
    {
        Car myCar = new Car();
        myCar.Speed = 60;
        myCar.Drive();
    }
}
Output
Driving at 60 km/h
⚠️

Common Pitfalls

Common mistakes when implementing interfaces include:

  • Not implementing all interface members, which causes a compile error.
  • Forgetting to mark implemented members as public, since interface members are always public.
  • Trying to instantiate an interface directly, which is not allowed.

Always ensure your class fully implements the interface contract.

csharp
using System;

interface IAnimal
{
    void Speak();
}

// Wrong: Missing implementation of Speak()
class Dog : IAnimal
{
    // Compile error: Dog does not implement Speak()
}

// Correct implementation
class Cat : IAnimal
{
    public void Speak()
    {
        Console.WriteLine("Meow");
    }
}
📊

Quick Reference

  • Use interface keyword to define an interface.
  • Use : to implement interface in a class.
  • Implement all interface members as public.
  • You cannot create instances of interfaces directly.
  • Interfaces help enforce a contract for classes.

Key Takeaways

Implement interfaces by using the ':' symbol and providing all required members in the class.
All interface members must be implemented as public in the class.
You cannot instantiate an interface directly; instantiate the implementing class instead.
Interfaces define a contract that classes must follow, improving code consistency.
Missing any interface member implementation causes a compile-time error.