Hi,
public IEnumerator<string> GetEnumerator() //This compiles fine even though I don't implement interface
will compile and also be usable in foreach statement as the C# Compiler takes additional steps to lookup a GetEnumerator method, see C# Language Specification:
5.3.3.16 Foreach statements and 10.14.5.1 The GetEnumerator method.
But thats "compiler magic" and not all compiler may implement it (Visual Basic does as far i've tested it). The clean way is to implement IEnumerable<T> and GetEnumerator methods:
using System.Collections;
using System.Collections.Generic;
class Spectrum : IEnumerable<string>
{
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
return _listfromUVtoIR ? UVtoIR : IRtoUV;
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<string>)this).GetEnumerator();
}
}
And with the explicit interface implementation it avoids cluttering the class with a public GetEnumerator method, as GetEnumerator is typically only used with foreach.
Regards, Elmar
No comments:
Post a Comment