✅ Interfaces in C#
Hello guys, I just learnt about interfaces, just to have an overview of what it is. From what I've understood, an interface is just a sort of "contract". That is, we say that in this particular interface, we want to have method X and property Y. Any class implementing that interface must also have method X and property Y but the way how we define the method body can be different.
I also read that "multi-inheritance" is not allowed I think in C# (just like in java I think). That's why, interfaces can be helpful because we can implement several interfaces.
Now, one thing I'm confuse about. If Class A implements interface A, if we instantiate Class A, since it's implementing interface A, it also have the "same type" as interface A? I'm asking that because I notice in an example:
Sometimes, the object person is passed as an argument to the method DoSomething while it expects the ISomething type as argument and not a person argument. But it works, why is that please.
Finally, can someone explain the use cases of interfaces and their importance please. For example if we don't create interfaces, say I have 3 classes: Animal, Dog and Cat.
What I did is, I create a "general" method in Animal, say
Then I would be able to override the MakeSound method just like we kind of would do in an interface. So what's the difference of implementing an interface or extending a class here please
I also read that "multi-inheritance" is not allowed I think in C# (just like in java I think). That's why, interfaces can be helpful because we can implement several interfaces.
Now, one thing I'm confuse about. If Class A implements interface A, if we instantiate Class A, since it's implementing interface A, it also have the "same type" as interface A? I'm asking that because I notice in an example:
Sometimes, the object person is passed as an argument to the method DoSomething while it expects the ISomething type as argument and not a person argument. But it works, why is that please.
Finally, can someone explain the use cases of interfaces and their importance please. For example if we don't create interfaces, say I have 3 classes: Animal, Dog and Cat.
What I did is, I create a "general" method in Animal, say
MakeSound. Dog and Cat extends Animal so MakeSound also exist in each respective classes.Then I would be able to override the MakeSound method just like we kind of would do in an interface. So what's the difference of implementing an interface or extending a class here please