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

Multiple interface implementation in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Sometimes a class needs to do many different jobs. Multiple interface implementation lets a class promise to do several different sets of tasks.

When a class needs to follow rules from more than one interface.
When you want to organize different behaviors separately and combine them in one class.
When you want to make sure a class can be used in different ways depending on the interface.
When you want to add new features to a class without changing its main code.
When you want to write flexible and reusable code.
Syntax
C Sharp (C#)
class ClassName : Interface1, Interface2, Interface3
{
    // Implement all interface members here
}

You separate multiple interfaces with commas.

The class must provide code for all methods and properties from all interfaces.

Examples
This class Person promises to do both Walk and Talk by implementing two interfaces.
C Sharp (C#)
interface IWalk
{
    void Walk();
}

interface ITalk
{
    void Talk();
}

class Person : IWalk, ITalk
{
    public void Walk()
    {
        Console.WriteLine("Walking...");
    }

    public void Talk()
    {
        Console.WriteLine("Talking...");
    }
}
The MultiFunctionDevice can both print and scan because it implements two interfaces.
C Sharp (C#)
interface IPrinter
{
    void Print();
}

interface IScanner
{
    void Scan();
}

class MultiFunctionDevice : IPrinter, IScanner
{
    public void Print()
    {
        Console.WriteLine("Printing document");
    }

    public void Scan()
    {
        Console.WriteLine("Scanning document");
    }
}
Sample Program

This program shows a MediaDevice that can both play and record media by implementing two interfaces. When run, it calls both methods.

C Sharp (C#)
using System;

interface IPlayable
{
    void Play();
}

interface IRecordable
{
    void Record();
}

class MediaDevice : IPlayable, IRecordable
{
    public void Play()
    {
        Console.WriteLine("Playing media");
    }

    public void Record()
    {
        Console.WriteLine("Recording media");
    }
}

class Program
{
    static void Main()
    {
        MediaDevice device = new MediaDevice();
        device.Play();
        device.Record();
    }
}
OutputSuccess
Important Notes

All interface methods must be implemented in the class, or the class must be marked abstract.

Interfaces only have method signatures, no code inside them.

Multiple interface implementation helps keep code organized and flexible.

Summary

Multiple interface implementation lets a class follow many sets of rules.

Use commas to list interfaces after the class name.

The class must write code for all interface methods.