
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
150
|
Chapter 3: Classes and Structures
Passing the Objects array in to the following method allows each Sort method to be
called from each object in the
Objects array:
public void SortAllObjects(object[] sortableObjects)
{
foreach (IMySort m in sortableObjects)
{
m.Sort( );
}
}
The foreach loop in this method is able to treat each object in the sortableObjects
array in the same way because each object in the sortableObjects array is cast to its
IMySort interface and used as such.
If the
foreach loop encounters a sortableObjects array that contains one or more
objects that do not implement the
IMySort interface, an InvalidCastException will be
thrown. To prevent an exception from being thrown, while at the same time allow-
ing the
foreach loop to iterate over all elements in the sortableObjects array, you can
use the following modified code:
public void SortAllObjects(object[] sortableObjects)
{
foreach (object o in sortableObjects)
{
IMySort sortObject = o as IMySort;
if (sortObject!= null)
{
sortObject.Sort( );
}
}
}
This modified method will now test each element of the sortableObjects array to
first determine whether it can be cast to an
IMySort interface. If it can be cast to this
interface type, the variable
sortObject will not be null and the if statement will
allow the
Sort method on that ...