To some extend interfaces reminds a lot of an abstract class. But there is some big differences.
- An interface can't contain any logic (not quite true as C# 8.0 introduces default implementations)
- A class can implement several interfaces, but only on inherit one class
- An interface says nothing about the internal state of a class
Advantage of interface:
- It is used to achieve loose coupling.
- It is used to achieve total abstraction.
- To achieve component-based programming
- Interfaces intertroduces a plug-and-play like architecture into applications.
An interfaces should be seen as a contract which define the public properties, methods, and events, which the class or struct must implement.
An object never can be an instance of an interface, but an object can be an instance of a class implementing one or more interfaces.
Interfaces is more or less the only type in Microsoft C# naming convension where prefixes is used in the naming.
So when naming an interface should the name be prefixed with an I. Eg. an interface for a mammal would would be named IMammal.
In this example does the interface IMammal tell us that all mammals have two properties: number of legs and the specie of the mammal, and that the mammal have the behavior of making a sound.
The example is quite simplified, but a key difference between a dog and a human (in this example) is the ability to make complex sounds (speak), so the implementation of human and dog differs a bit, but they still implement to the same contract (interface). This contract is used by the DisplayMammal method to display the information on the mammal.
Question to think about: What could we do if the mammal does not have any legs? Like a whale