I am writing a custom ConfigurationElementCollection for a custom ConfigurationHandler in C#.NET 3.5 and I am wanting to expose the IEnumerator as a generic IEnumerator.
What would be the best way to achieve this?
I am currently using the code:
public new IEnumerator<GenericObject> GetEnumerator()
{
var list = new List();
var baseEnum = base.GetEnumerator();
while(baseEnum.MoveNext())
{
var obj = baseEnum.Current as GenericObject;
if (obj != null)
list.Add(obj);
}
return list.GetEnumerator();
}
Cheers
I don’t believe there’s anything in the framework, but you could easily write one:
It’s tempting to just call
Enumerable.Cast<T>from LINQ and then callGetEnumerator()on the result – but if your class already implementsIEnumerable<T>andTis a value type, that acts as a no-op, so theGetEnumerator()call recurses and throws aStackOverflowException. It’s safe to usereturn foo.Cast<T>.GetEnumerator();whenfoois definitely a different object (which doesn’t delegate back to this one) but otherwise, you’re probably best off using the code above.