Hi,
Suppose you have an application that has two types of people: Customer and Employee. Both Customer and Employee can subscribe to an event. The procedure of subscribing is different. Customers need to pay and subscbribe where as Employees only need to subscribe.
When you have a list of objects (both Customers and Employees) that want to subscribe, you need to check for each object what type of person it is before knowing how it needs to subscribe to the event. If at a certain point you add a different person type, you need to add additional code in the calling class.
With interfaces this can be a lot easier. First we create an interface named IPerson. This interface has a method named Subscribe. Than we make sure that all the person types implement this interface. The method Subscribe is implemented in the classes (Customer, Employee).
If we need to have a list of persons we create the list as follow:
List<IPerson> myList = new List<IPerson>();
IPerson person1 = new Customer();
myList.Add(person1);
IPerson person2 = new Employee();
myList.Add(person2);
Now when we loop through the list, we can use IPerson.Subscribe() to subscribe a person. This will cause the .NET framework to call the Subscribe method from the objects class.
Interfaces make it easier to extend this type of code. When a different person type is needed, you only need to add a class that implements the IPerson interface.
Let me know if the above is not clear.
Greetz,
Geert
Geert Verhoeven
Consultant @ Ausy Belgium
My Personal Blog