
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Calling the Same Method on Multiple Object Types
|
149
public class ObjectContainer : IMySort
{
public void Sort( )
{
// Do object type sorting here.
Console.WriteLine("Objects sorted");
}
}
The SortAllObjects method accepts an array of objects:
public void SortAllObjects(IMySort[] sortableObjects)
{
foreach (IMySort m in sortableObjects)
{
m.Sort( );
}
}
If this method is called as follows:
Obj.SortAllObjects(new IMySort[3] {new CharContainer( ),
new NumberContainer( ),
new ObjectContainer( )});
the following is displayed:
Characters sorted
Numbers sorted
Objects sorted
Discussion
The foreach loop is useful not only for iterating over individual elements in a collec-
tion or an array, but also in iterating over a specific interface implemented by each
element in a collection or array. Using this technique, interface members may be
used in a similar manner on each element, even if the elements are unrelated object
types. Consider the following array of objects:
Object[] objs = new Object[6] {new CharContainer( ),
new NumberContainer( ),
new CharContainer( ),
new ObjectContainer( ),
new NumberContainer( ),
new ObjectContainer( )};
This array contains several objects of differing types. The one thread of similarity
that runs through each type is the implementation of the
IMySort interface, defined ...