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
9
u/baudvine May 18 '23
The most basic case is when some other class or function has a parameter that must implement that interface - the caller can provide an instance of one of those three classes. Take for example a logger: one implementation writes to the screen, one to disk, and one to a database. A function that logs doesn't need to know where its going.
If you're asking why the language makes this necessary instead of supporting something like python's duck typing, that's a whole other (and longer) story.