-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?

6
  • why minus could you help me\ Commented Oct 3, 2019 at 5:03
  • 1
    I think this is because it's unclear what you asking for. We can't say why do you use your interfaces like this Commented Oct 3, 2019 at 5:06
  • Please, Take a look at the answer to the question Creating objects from an interface in C# Commented Oct 3, 2019 at 5:07
  • also, there is a lack of formatting and a lot of typos in your code, so it is almost unreadable Commented Oct 3, 2019 at 5:09
  • Because you can _Iobjrepo = new AnotherRepo() and not break existing code that relies on it, for one reason. Commented Oct 3, 2019 at 5:10

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.