Why to use Interfaces Whenever Possible in C#

The .NET Framework contains both classes and interfaces. When you write routines, you will find that you probably know which .NET class you're using. However, your code will be more robust and more reusable if you program using any supported interfaces instead of the class you happen to be working with at the time. Consider this code:

private void LoadList (object [] items,
ListBox l) {
for (int i = 0; i < items.Length;i++)
l.Items.Add (items[i].ToString ());
}

This function loads a ListBox from an array of any kind of objects. The code is limited to an array only. Suppose that later you find that objects are stored in a database, or in some other collection. You need to modify the routine to use the different collection type. However, had you written the routine using the ICollection interface, it would work on any type that implements the ICollection interface:

private void LoadList (ICollection items,
ListBox l) {
foreach (object o in items)
l.Items.Add (o.ToString ());
}

The ICollection interface is implemented by arrays, and all the collections in the System.Collection. In addition, multidimensional arrays support the ICollection interface. If that's not enough, the database .NET classes support the ICollection interface as well. The function written using the interface can be reused many more ways without any modification.

No comments:

Post a Comment