CHAPTER 8 WORKING WITH INTERFACES
Note In Chapter 9, you will learn about the role of generics and the System.Collections.Generic
namespace. As you will see, this namespace contains generic versions of IEnumerable/IEnumerator that provide
a more type-safe way to iterate over subobjects.
Classes or structures that support this behavior advertise that they are able to expose contained
subitems to the caller (in this example, the foreach keyword itself). Here is the definition of this standard
.NET interface:
// This interface informs the caller
// that the object's subitems can be enumerated.
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
As you can see, the GetEnumerator() method returns a reference to yet another interface named
System.Collections.IEnumerator. This interface provides the infrastructure to allow the caller to traverse
the internal objects contained by the IEnumerable-compatible container:
// This interface allows the caller to
// obtain a container's subitems.
public interface IEnumerator
{
bool MoveNext ();
// Advance the internal position of the cursor.
object Current { get;}
// Get the current item (read-only property).
void Reset ();
// Reset the cursor before the first member.
}
If you want to update the Garage type to support these interfaces, you could take the long road and
implement each method manually. While you are certainly free to provide customized versions of
GetEnumerator(), MoveNext(), Current, and Reset(), there is a simpler way. As the System.Array type (as
well as many other collection classes) already implements IEnumerable and IEnumerator, you can simply
delegate the request to the System.Array as follows:
using System.Collections;
...
public class Garage : IEnumerable
{
// System.Array already implements IEnumerator!
private Car[] carArray = new Car[4];
public Garage()
{
carArray[0] =
carArray[1] =
carArray[2] =
carArray[3] =
}
304
new
new
new
new
Car("FeeFee", 200);
Car("Clunker", 90);
Car("Zippy", 30);
Car("Fred", 30);