0
0
C Sharp (C#)programming~5 mins

Implementing interfaces in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Interfaces help us define a set of rules that classes must follow. Implementing interfaces means a class promises to provide specific actions or behaviors.

When you want different classes to share the same set of actions but with their own details.
When you want to make sure a class has certain methods before using it.
When you want to write code that works with many types of objects in a similar way.
When you want to separate what a class does from how it does it.
Syntax
C Sharp (C#)
interface IExample
{
    void DoWork();
}

class MyClass : IExample
{
    public void DoWork()
    {
        // method details here
    }
}

Use the interface keyword to define an interface.

Use a colon : to show a class implements an interface.

Examples
This example shows an interface IAnimal with a method Speak. The class Dog implements it by writing "Woof!".
C Sharp (C#)
interface IAnimal
{
    void Speak();
}

class Dog : IAnimal
{
    public void Speak()
    {
        Console.WriteLine("Woof!");
    }
}
Here, IShape requires a method to get area. Circle implements it using its radius.
C Sharp (C#)
interface IShape
{
    double GetArea();
}

class Circle : IShape
{
    public double Radius { get; set; }

    public double GetArea()
    {
        return Math.PI * Radius * Radius;
    }
}
Sample Program

This program defines an interface IVehicle with a method Drive. The class Car implements this method. In Main, we create a Car as an IVehicle and call Drive.

C Sharp (C#)
using System;

interface IVehicle
{
    void Drive();
}

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

class Program
{
    static void Main()
    {
        IVehicle myCar = new Car();
        myCar.Drive();
    }
}
OutputSuccess
Important Notes

All methods in an interface are public by default and cannot have bodies (unless using default interface methods in newer C# versions).

A class can implement multiple interfaces by separating them with commas.

Interfaces help with writing flexible and testable code.

Summary

Interfaces define what methods a class must have, without saying how.

Implementing an interface means writing those methods in your class.

This helps different classes work together in a clear way.