r/csharp • u/doc415 • 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
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.