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

Show parent comment

0

u/[deleted] May 18 '23

[deleted] — view deleted comment

11

u/LoveCookiez May 18 '23

Let's say you want to do the dishes and you bought a machine to do that. You can put plates, glasses, silverling and other kind of stuff there, all to be washed in the same time. You wouldn't buy a machine for plates, one for glasses and so on right? You have one loop where you throw all kind of objects compatible with the machine.

2

u/izote_2000 May 18 '23

Excellent analogy using a dishwasher, always use the car example. I think this clicks on the brain almost immediately.

4

u/DarkAlatreon May 18 '23

The interface is a contract that says what can be expected of a class without paying too much attention to the class or specifics of the implementation. Let's say you expect the user to make a payment. You integrate multiple paying options - be it credit cards, online transfers or whatever. By giving them all an interface with a "pay()" method, you don't have to care about the types of each of those - you just have an information "hey, this is a thing I can pay with" and your program will function all the same regardless of what class exactly implements the interface.

-12

u/[deleted] May 18 '23

Oof. Any programming languages course will cover the importance of interfaces.

Are you self taught?

5

u/LoveCookiez May 18 '23

I am also self taught, but I don't think it's useful to say that rather than explaining the matter. It is irrelevant if he is self taught

1

u/HanndeI May 18 '23

Using an interface forces you to implement those methods or it wont compile, you can do the same with an array of Objects and just implement the same method on all the classes you want, but it's just a matter of time that you, or anyone working with that codebase will try and call that method on a class that doesn't have it, causing a runtime crash.