-6

In one of my interviews I face this problem as why you use your interface as below mention

Interface

Interface Irepo{
    void add(int a, int b);
}

Repo.cs

Public Class Repo:Irepo{
    public  void add(int a, int b){
}

HomeContrller

Public Clas HomeController:ApiController{

    Private readonly Irepo _Iobjrepo;
    public HomeController(){
        _Iobjrepo =new Repo();
    }
}

Please help me why to use Irepo in constructor of HomeController. What is its use?

Stefan
  • 652
  • 5
  • 19

2 Answers2

1

Simple example of using interfaces which hopefully explains it a bit:

Interface

interface IAnimal
{
    bool HasFur;
}

Interface implementations

class Cat : IAnimal
{
    public bool HasFur => true;

    public Cat()
    {
    }
}

class Fish : IAnimal
{
    public bool HasFur => false;

    public FIsh()
    {
    }
}

Usage

IAnimal anyTypeOfAnimal = new Cat();
IAnimal anotherAnimal = new Fish();

public void TestInterface(IAnimal obj)
{
     Console.Log(obj.HasFur);
}

TestInterface(anyTypeOfAnimal.HasFur); //True
TestInterface(anotherAnimal.HasFur); //False

If you declare a variable of type IAnimal you can store any type that implements the interface. This can come in handy when you don't now which type of IAnimal you are getting and it doens't because in this example you just want to know if the animals have fur.

Stefan
  • 652
  • 5
  • 19
1

In this context, one reason would be improve testability. Later when you write unit tests for your Home Controller, you do not want to use the actual Repo object inside Home controller. Because you don't want to read/write to the actual database when executing unit tests. The Interface IRepo will allow you to inject a "fake" or mock of the actual repo.

Ross Brigoli
  • 676
  • 1
  • 12
  • 22