If you plan on doing any back-end development, it's going to be important you know about interfaces. At first they seem kind of weird, but once you understand what they are you'll become more powerful than you've ever been. |
You'll see interfaces a lot in C# because it doesn't let you inherit multiple classes. That's where interfaces come in. They let you implement the same methods and variables across different classes. An interface is kind of like a list of things that your class has to have.
When you use an interface on your classes, you have to write the implementation of the methods in your class. So you're probably wondering why you should even bother with interfaces if you still have to write separate implementation for everything.
It really comes down to the fact that you can't inherit multiple classes in C#. If you only need to inherit one class, you could use something like an abstract class. The thing that makes interfaces so powerful is the fact you can have multiple interfaces on the same class. That way when your code is compiling it knows what to expect at run-time.
Let me try using an example of an interface. Say you have a Chef class. It should have a method called Cook that can be used to cook any class of food that implements the ICookable interface. The Chef class shouldn't have a CookItalian, CookThai, or Cook(X) method for every kind of class that has the same basic operations.
Looking at this example it might not look like interfaces are much different from inheritance but there is a big difference. With inheritance, you are saying that your class is what it inherits. While an interface just says your class is implementing the methods in the interface.
Another thing that most people get confused about with interfaces is if they should be implemented by more than one class. Some of you might be saying that's not true, but hear me out. There's been a weird push to decouple every bit of code you possibly can and we do that by using interfaces.
If you go through some code, I bet you'll find that a lot of classes are only implementing one interface and none of the interfaces are the same. Have you thought about why that is? If you only have one class using a set of methods, why would you need a separate interface to do that?
For testing and dependency injection! That's why we use interfaces the way we do. It's not necessarily the "right" way to use them but it gets the job done. Interfaces really make testing easy because you can mock up stuff without needing to get rid of a lot of class dependencies. As for dependency injection, it's used to control which implementation of an interface should be used.
Interfaces are a little obscure until you work with them for a while and even then they're still weird. I just hope this helped bring you a little clarity about what they are and why we use them.
Related Articles -
web development, programming, beginners, csharp,