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
This works for me.
You can use
OfType<T>
andCast<T>
.To get an
IEnumerator<T>
instead of anIEnumerable<T>
you can just make a call toGetEnumerator()
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>
andT
is 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();
whenfoo
is definitely a different object (which doesn't delegate back to this one) but otherwise, you're probably best off using the code above.I was running into the same Stack Overflow problem mentioned is some of the comments. In my case it was due to the fact that the GetEnumerator call needed to be to the base.GetEnumerator otherwise you loop within your own GetEnumerator redefinition.
This is the code that was Throwing the Stack Overflow. The use of the foreach statement call the same GetEnumerator function I'm trying to overload:
I've ended up with a simplified version of the original post as you don't need to use a List holder.
IEnumerable<T>
already derives fromIEnumerable
so there's no need to do any conversion. You can simply cast to it...well actually it's implicit no cast necessary.Going the other way round isn't much more difficult with LINQ: