Forum General

c# interfaces - why?

AndyFlisherAndyFlisher GBBeta, University ✭✭✭✭

This is more of a C# question than a Mono / Xamarin one, and probably a case of not having built a project big enough, or complex enough to make the use case for interfaces obvious, but what is their selling point, how is it going to make my life easier. Can someone show / describe an example that will set off that lightbulb moment in my head where it all becomes clear and obvious (and I feel silly!)

At the moment, through classes, their functions, and events I've achieved all that I need to - so what am I missing?



  • SteveFlackSteveFlack GBMember ✭✭

    It allows you to separate the behaviour from the implementation. For example, in a cross platform app you may have a UI component that will be implemented differently on Android (with a Fragment say) than on iOS (with a UIViewController). You can't use subclassing in this case but you could use an interface that would stipulate that they would behave the same.

    You could then use a service locater in the common code to say "I want an object that implements such and such interface". The platform specific code would've registered the implementation for the interface.

  • SKallSKall USMember ✭✭✭✭

    Andy, look up design pattern called "Inversion of Control". You might have seen "IoC" somewhere in someones code. That pattern should give you more info why/how interfaces are useful.

  • GuillermoGutierrezGuillermoGutierrez ESMember ✭✭✭

    It's also essential to improve the testability of the code. If you use the class instead of the interface, you cannot provide a mock implementation that allows you to test edge cases and run backwards compatibility tests.

    Imagine testing a class that uses a database connection. You would need to build the database schema and have the database server running just to test that class.

  • AndyFlisherAndyFlisher GBBeta, University ✭✭✭✭

    Cheers guys, I'll have a look through and see if I can make a use case in my head, having spent 15 years in PHP, it's variations of OOP and having nothing similar I tend to construct things in a certain way, so trying to break the habit!

  • Uncle Bob Martin does a good job of describing this:

Sign In or Register to comment.