Why are interfaces useful

interfaces

I have been studying and coding in C# for some time now. But still, I can't figure the usefulness of Interfaces. They bring too little to the table. Other than providing the signatures of function, they do nothing. If I can remember the names and signature of the functions which are needed to be implemented, there is no need for them. They are there just to make sure that the said functions(in the interface) are implemented in the inheriting class.

C# is a great language, but sometimes it gives you the feeling that first Microsoft creates the problem (not allowing multiple inheritance) and then provides the solution, which is rather a tedious one.

That's my understanding which is based on limited coding experience. What's your take on interfaces? How often you make uses of them and what makes you do so?

Best Answer

They are there just to make sure that the said functions (in the interface) are implemented in the inheriting class.

Correct. That's a sufficiently awesome benefit to justify the feature. As others have said, an interface is a contractual obligation to implement certain methods, properties and events. The compelling benefit of a statically typed language is that the compiler can verify that a contract which your code relies upon is actually met.

That said, interfaces are a fairly weak way to represent contractual obligations. If you want a stronger and more flexible way to represent contractual obligations, look into the Code Contracts feature that shipped with the last version of Visual Studio.

C# is a great language, but sometime it gives you the feeling that first Microsoft creates the problem(not allowing multiple inheritance) and then provides the solution, which is rather a tedious one.

Well I'm glad you like it.

All complex software designs are a result of weighing conflicting features against each other, and trying to find the "sweet spot" that gives large benefits for small costs. We've learned through painful experience that languages that permit multiple inheritance for the purposes of implementation sharing have relatively small benefits and relatively large costs. Permitting multiple inheritance only on interfaces, which do not share implementation details, gives many of the benefits of multiple inheritance without most of the costs.