Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we should implement Interface?

Tags:

c#

oop

interface

Implementing Interface just provide the skeleton of the method. If we know the exact signature line of that method, in this case
what is the requirement to implement Interface?
This is the case in which Interface has been implemented

interface IMy
{
    void X();
}
public class My:IMy
{
    public void X()
    {
        Console.WriteLine("Interface is implemented");
    }
}

This is the case in which Interface has not been implemented

public class My
{
    public void X()
    {
        Console.WriteLine("No Interface is implemented ");
    }
}


My obj = new My();
obj.X();

Both the approaches will produce the same result.
what is the requirement to implement Interface?

like image 671
jams Avatar asked Dec 04 '22 08:12

jams


1 Answers

The purpose of interfaces is to allow you to use two different classes as if they were the same type. This is invaluable when it comes to separation of concerns.

e.g. I can write a method that reads data from an IDataReader. My method doesn't need to know (or care) if that's a SqlDataReader, and OdbcDataReader or an OracleDataReader.

private void ReadData(IDataReader reader)
{
....
}

Now, lets say I need that method to process data coming from a non-standard data file. I can write my own object that implements IDataReader that knows how to read that file, and my method again, neither knows nor cares how that IDataReader is implemented, only that it is passed an object that implements IDataReader.

Hope this helps.

like image 83
Binary Worrier Avatar answered Dec 22 '22 23:12

Binary Worrier