Description
Andrew Troelsen has published two .Net programming books from Apress: C# and the .NET Platform and Visual Basic .NET and the .NET Platform. You can check their websites for code download and errata. Since these are two popular books you may have already bought one. Usually you do not need to buy both of them as the second book essentially duplicates the same content as the first one. And if the first book has some bugs in its code, the second book will simply repeat it.
This article examines code problem in chapter 4 (for C#)/chapter 5(for VB.Net) of the two .Net books. Project ObjEnum for Building a Custom Enumerator (IEnumerable and IEnumerator) does not implement Reset method correctly. Reset method, defined by IEnumerator interface, should set the enumerator to its initial position, which is before the first element in the collection. Unfortunately, the code in two books set the enumerator at the first element in the collection, which is incorrect.
Let's see the original implementation details:
// Implementation of IEnumerator.
public bool MoveNext()
{
if(pos < carArray.Length)
{
pos++;
return true;
}
else
return false;
}
public void Reset()
{
pos = 0;
}
public object Current
{
get { return carArray[pos]; }
}
Here is the corrected implementation:
// Implementation of IEnumerator.
bool IEnumerator.MoveNext()
{
if(pos < carArray.Length)
{
pos++;
return true;
}
else
return false;
}
void IEnumerator.Reset()
{
pos = -1;
}
object IEnumerator.Current
{
get
{
if (pos < 0 || pos >=carArray.GetLength(0))
throw (new System.InvalidOperationException());
else
return carArray[pos];
}
}