Information Technology Reference
In-Depth Information
I wrote that last version to show you that interfaces really can't contain
implementation. You can emulate that by using extension methods. LINQ
does that by creating several extension methods on IEnumerable<T> in
the System.Linq.Enumerable class.
That brings me to the topic of using interfaces as parameters and return
values. An interface can be implemented by any number of unrelated
types. Coding to interfaces provides greater flexibility to other developers
than coding to base class types. That's important because of the single
inheritance hierarchy that the .NET environment enforces.
These three methods perform the same task:
public static void PrintCollection<T>(
IEnumerable <T> collection)
{
foreach (T o in collection)
Console .WriteLine( "Collection contains {0}" ,
o.ToString());
}
public static void PrintCollection(
System.Collections. IEnumerable collection)
{
foreach ( object o in collection)
Console .WriteLine( "Collection contains {0}" ,
o.ToString());
}
public static void PrintCollection(
WeatherDataStream collection)
{
foreach ( object o in collection)
Console .WriteLine( "Collection contains {0}" ,
o.ToString());
}
The first method is most reusable. Any type that supports IEnumerable<T>
can use that method. In addition to WeatherDataStream, you can use
List<T>, SortedList<T>, any Array, and the results of any LINQ query.
The second method will also work with many types, but uses the less prefer-
able nongeneric IEnumerable. The final method is far less reusable. It can-
 
Search WWH ::




Custom Search