Interfaces determine that a class MUST be able to do something. This means that you know that the object you are working on will do what you want to do. This allows you more freedom and benefits of OOP. This is a deep topic, but a very simple example:
public interface IAnimal { string Speak(); } public class Dog : IAnimal { public string Speak() { return "Woof, woof"; } } public class Cat : IAnimal { public string Speak() { return "Meow"; } } public class Parrot : IAnimal { public string Speak() { return "Sqwark!"; } }
Then you can use any animal that you like!
class Program { static void Main(string[] args) {
It also allows you to go into things like Inversion Of Control , where you could take such an item and you could pass the dog, cat or parrot, and the method will always work, not knowing or caring about what kind of animal it is :
public void ShoutLoud(IAnimal animal) { MessageBox.Show("Shout " + animal.Speak()); }
This makes ShoutLoud a single testable because you can use a mock object rather than a real animal. This basically makes your code flexible and dynamic, rather than rigid and tightly coupled.
In addition, Matthew's question expands. In C #, you can only inherit one base class, but you can have multiple interfaces. So you could:
public class Dog : IAnimal, IMammal, ICarnivor
This allows you to have small interfaces (recommended) that then allow you to create, giving you maximum control over what the item can / should do.
Belogix May 30 '13 at 9:34 a.m.
source share