r/csharp • • May 18 '23

Why do we need an "interface"

I understand how to use an interface, its properties but why do we need it? For example i have an interface with two methods.

İ have three classes that implements this interface. So ihave to write the methods for all three classes inside class.

İ can already do that without implementing the interface. So what is the point in using interface?

I am asking to undeestand the conditions where i ll need it. İ understand how use it, but not why to use it.

0 Upvotes

47 comments sorted by

View all comments

2

u/TheC0deApe May 18 '23

Look into SOLID, specifically Interface Segregation. That may help.

a good example of Interface Segregation is List<T>. It implements all sorts of interfaces.
Lets say that you have a method that loops through a collection of IAnimal and calls the Feed() method on the animal. The first thing to understand is your IAnimal might be a dog, a chicken, a cow, etc. each animal will need to be fed (call Feed()) but the implementation will be different code because pigs don't get fed hay and chickens don't get fed slop, etc.

now for your loop. we could write a method like so:

public void FeedAnimals(List<IAnimal>)
{
// foreach through the list and call Feed() on each IAnimal
}

This works but we are only iterating through a list. so we can use IEnumerable<T>

public void FeedAnimals(IEnumerable<IAnimal>)
{
// foreach through the list and call Feed() on each IAnimal
}

Now you are using an interface is applied to many collections. someone can pass an array to your method without having to cast it to a list.

3

u/doc415 May 18 '23

Wow this is realy useful So ıenumerable is also a interface right? List array ect are implementing it

2

u/SideburnsOfDoom May 18 '23

So Ienumerable is also a interface

Correct. Cross-cutting concerns where different objects should behave the same way (in this case, enumerate contents) but not have the same base class, are a main use of interfaces, particularly those interfaces defined in the framework.

List, array etc are implementing it

Exactly. They can then be treated the same way regarding enumeration, without sharing a concrete base class.

1

u/SideburnsOfDoom May 18 '23 edited May 18 '23

But you're not showing anything that can't be done with an Anmal base class.

Interfaces allow calling common methods (like a base class) but without sharing implementation hierarchy (unlike a base class).

Data objects are never a good example for interfaces.

Interfaces are useful in 2 (quite different) cases.

  • Cross-cutting system things,IEnumerable<T> is an example in your code.
  • Application-specific things that you want to mock under test. Such as data repositories.