Wednesday, March 08, 2006

 

Enumerators to nowhere

ASP.NET 2.0 Enumerator objects and their derivatives can point to nowhere. That is their initial state when created by GetEnumerator() methods on collection objects, and it is their final state after moving through all the items of a collection. Evaluating an Enumerator to nowhere will lead to an exception. How does one otherwise detect that an Enumerator points to nowhere?

As often happens, Microsoft ASP.NET 2.0 documentation is opaque. However, it offers a hint that while the Current property of an Enumerator to nowhere provides a valid KeyValuePair, the Value property of that object is undefined.

Although Microsoft does not document this, when the type of Key is numeric, the Key value will be zero; and when it is a string, the Key value will be empty. That behavior does not suffice, since such Key values might be allowed.

To detect an Enumerator to nowhere, the reliable approach is to test the Value property of Current for null, as in this abbreviated example:

SortedDictionary<...> oMap = new SortedDictionary<...>();
SortedDictionary<...>.Enumerator oMapEnum = oMap.GetEnumerator();
if (oMapEnum.Current.Value == null)
. . .

Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]