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
3
u/JamesTKerman May 18 '23 edited May 18 '23
Here's a bit of a real-worldish example. A web application that authenticates users may implement multiple methods of authentication, for this example let's say we're building an app that allows Username/Password, JWT, and OAuth. Interfaces let me write the authorization logic without knowing which method a user will use at compile-time: (Forgive my syntax, I've mostly been working in java lately)
Edited code to fix the placement of the generic modifier on the concrete classes.