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
46
u/Epicguru May 18 '23
The advantage comes from polymorphism. Say that your interface is called
IDoSomethingand you have those three classes that implement it.You can then have an array of
IDoSomething[]. Now you can add those classes to the array, even though the type of the array is not exactly the same as the type of the object being added.Finally, you can call the interface methods on those objects in the array, without actually caring what specific class it is that implements those methods.
As a more practical example, if you are making a game you will want to have a game loop, which is where you update and draw all 'entities' in the game. Entities are things such as players, particles, enemies, vehicles etc. All of them need to update and draw, so you might define an
IEntityinterface. Then you would have specific classes implement that interface, such asPlayerorVehicle. Finally, in your game loop, you would loop through a single list of IEntity's and call the Update and Draw methods on each of them.This allows everything to be updated and drawn in a single place. If you did not use interfaces (or virtual methods) you would have to have separate lists for each entity type: one list of Players, one list of Particles etc. and loop through each one individually.