views:

21

answers:

1

I have a generic class that implements IList

public class ListBase<T>: IList<T>, IListBase{

   IEnumerator<T> GetEnumerator(){ ....
   System.Collections.IEnumerator GetEnumerator(){ return GetEnumerator();}

}

The IListBase is an interface I use to access methods on this class for cases where I don't know the type of T at runtime.

I need to implement a second Enumerator via this IListBase interface which will iterate the members of my class and return them cast as a base type that all members will implement.

I've tried having the IListBase implement my specific Enumerator:

public interface IListBase: IEnumerable<MemberBaseType> { ....

But this blows up due to the fact that T and MemberBaseType could be the same in some instances. Even adding the enumerator members to the interface and then using explicit declarations doesnt help this problem.

I then tried adding another method to call for just getting specific IEnumerator, but the compiler then complains about not finding a public GetEnumerator method to use with this type...

Any recommendations for adding this secondary enumerator so they don't collide with each other?

A: 

Having two enumerators at the same level that do different things is (IMO) a bad idea. You can probably force it, but as soon as someone casts your type (especially if casting to the non-generic interface) it is largely guesswork which they will get.

I would recommend (instead) making this available via a property, for example .Members, where .Members offers this enumeration. Then no ambiguity of intent, and no compiler unhappiness. So I could use:

foreach(var member in list.Members) { /* add columns */ }
foreach(var item in list) { /* add rows */ }

You might also consider ITypedList, which may have some relevence here, especially if you want to data-bind to your list (this isn't necessary if T by itself defines everything cleanly).

In short:

public interface IListBase {
    IEnumerable<MemberBaseType> Members {get;}
}
Marc Gravell
Marc, Im not entirely sure why, but when I add a method (or property like you have here) that returns an IEnumerable<MemberBaseType>, the compiler complains about IEnumerable<MemberBaseType> not containing a GetEnumerator() method... not sure whats up?
boomhauer
A message like that *usually* means I've selected the wrong option in resharper, and it has created a *new* type somewhere (rather than add the correct using directive)... might want to double-check that?
Marc Gravell
I actually wound up adding a small class that derives IEnumerable<MemberBaseType> and am returning it from a method call now. Not beautiful, but seems to work. Thanks for the help!
boomhauer
Marc, giving you the answer, but actually impelmented a bit differently - just had a method that returned IEnumerator<MemberBasseType>... I had IEnumerable<..> returned before and this was causing my headaches. Thx
boomhauer