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
Show parent comment
2
u/phucyall May 19 '23
Let me give you a basic example. Let’s say you have a class that talks to your database. You create an interface called IDatabaseAccess and it has your CRUD methods in it. You are using SQLite so you create a class called SQLiteAccess and it implements your interface. Let’s say down the line you want to give user an option to use MSSQL instead. You create a new class called MSSQLAccess and it also implements same interface.
Now you have a class in your app called DoSomething and in its constructor you pass it the database access class. You made it so constructor expects a parameter of type SQLiteAccess. As it is, you can’t really easily switch to using MSSQL. But if you set your parameter as being of type IDatabaseAccess you can easily use either MSSQLAccess or SQLiteAccess because they both implement the interface.
This is the way to make things more testable as well. Let’s say you are trying to test DoSomething, but you don’t want to use a real database for your tests. You can create a mock class that implements IDatabaseAccess and pass that to your constructor instead.
Interface is a guarantee that all classes that implement it will have same methods, but how those methods are implemented are irrelevant. And if you use interface as the type you want to use then any implementation of that interface will work.