20

I think I understand why IEnumerable<T> inherit from IEnumerable, after reading the post: Why does IEnumerable<T> inherit from IEnumerable?

However, I am not sure how best to implement the non-generic method when appling 2 generic interfaces? Here is an example of the code I am writting:

public interface IComponentA { /* ... Interface A Code ... */ }

public interface IComponentB { /* ... Interface B Code ... */ }

public class ComponentModel: IEnumerable<IComponentA>, IEnumerable<IComponentB>
{
    public ComponentModel() { }

    private List<IComponentA> ListOfComponentA = new List<IComponentA>();
    private List<IComponentB> ListOfComponentB = new List<IComponentB>();

    // ... Some public methods to add and remove components (for A and B).

    IEnumerator<IComponentA> IEnumerable<IComponentA>.GetEnumerator()
    {
        return ListOfComponentA.GetEnumerator();
    }

    IEnumerator<IComponentB> IEnumerable<IComponentB>.GetEnumerator()
    {
        return ListOfComponentB.GetEnumerator();
    }

    // The fact that IEnumerable<T> inherits from the non-generic IEnumerable
    // now means I have to deal with this.
    IEnumerator IEnumerable.GetEnumerator()
    {
        // Throwing a NotImplementedException is probably not a good idea
        // so what should I put in here?
        throw new NotImplementedException();
    }
}

Suggestions of what to put in the non-generic method are welcome please.

Community
  • 1
  • 1
Ben
  • 3,241
  • 4
  • 35
  • 49
  • 1
    In what way does it make sense to iterate over two collections at once? I'm confused. – Jeremy McGee Oct 21 '11 at 14:41
  • 1
    I do worry it would be confusing, have you considered just exposing a read-only collection (or an iterator) as a property that they can iterate on? – James Michael Hare Oct 21 '11 at 14:43
  • +1 on James's suggestion: expose properties that allow iteration over each collection. Otherwise it's *very* confusing. For example, this simple and intuitive code won't even compile: `foreach (var x in myComponentModel) { }` – dlev Oct 21 '11 at 14:46
  • 1
    @Jeremy - please remember, if I knew what I was doing then I wouldn't have to ask. Please don't be confused. – Ben Oct 21 '11 at 16:27

4 Answers4

21

I probably wouldn't do that, myself. It can be confusing for a user to have the enumerator enumerate over different things depending on the interface reference calling it, and of course the issue of what the generic returns as well.

Instead, you could just expose a read-only-ish version of the lists as an iterator:

public class ComponentModel
{
    public ComponentModel() { }

    private List<IComponentA> ListOfComponentA = new List<IComponentA>();
    private List<IComponentB> ListOfComponentB = new List<IComponentB>();

    public IEnumerable<IComponentA> AComponents 
    {
        get { return ListOfComponentA.Skip(0); }
    }

    public IEnumerable<IComponentB> BComponents
    {
        get { return ListOfComponentB.Skip(0); }
    }

    ...
}

By using the Skip(0) you return an iterator, and it prevents them from casting back to List<IComponentA> and modifying the List out from under you.

You could also use a ReadOnlyCollection of course, but those are kinda clunky since they throw when you try to do mutating ops.

So now, you can iterate over either:

foreach(var a in myModel.AComponents)
{
    ...
}

foreach(var b in myModel.BComponents)
{
    ...
}

Also, IF A and B component lists always have the same length, you could have an enumerator over a Tuple of them in .NET 4.0 and using the Linq Zip() method:

public IEnumerable<Tuple<IComponetA, IComponetB>> Components
{
    get
    {
        return ListOfComponentA.Zip(ListOfComponentB, (a,b) => Tuple.Create(a,b));
    }
}
James Michael Hare
  • 37,767
  • 9
  • 73
  • 83
  • Thanks James - this seems to be exactly what I need! – Ben Oct 21 '11 at 15:37
  • If A and B are always the same length, I would make the class itself `IEnumerable>` instead of using the `.Components` to access that. – configurator Oct 22 '11 at 18:04
  • True, you could. It really depends on how the OP wants to access it. That would be consistent with Dictionary which is an IEnumerable> but also has Keys and Values properties which are IEnumerable and IEnumerable respectively. – James Michael Hare Oct 24 '11 at 14:24
  • 1
    @configurator I agree with you and would also recommend this **IF** the respective elements in each tuple are related to each other. Otherwise it makes absolutely no sense. (I know it's implied, but I just wanted to stress this!) – AnorZaken Jul 16 '15 at 09:44
17

The accepted answer is exactly right; you should implement things that have two sequences as having two sequences, not as being two sequences.

The reason given thus far about why it is a bad idea is sufficient, namely, that it is generally less confusing when you choose composition over inheritance. However, I think it is valuable to point out that there is another reason why implementing two different IEnumerable<T> interfaces is a really bad idea: we added generic covariance to IEnumerable<T> in C# 4.

Generic covariance means that you can pass a sequence of Turtles to a method that takes a sequence of Animals, because Turtles are Animals. So what then does the runtime do in this case?

class Weird : IEnumerable<Turtle>, IEnumerable<Giraffe> { ... }
...
Weird weird = whatever;
foreach(Animal animal in weird)
{
    ...

Is animal a turtle or a giraffe? The runtime has to pick one of them, and it is completely unclear which one is the right one to pick. This is one of the rare situations in which the C# specification does not say what happens; this is implementation-defined behaviour. Avoid, avoid, avoid.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • 1
    Interesting point. I think understand what you are saying. Can you please comment on this suggestion: `class HerdOfGiraffes : IEnumerable, IEnumerable`, after all a giraffe _is an_ animal and a giraffe _is a_ quadruped. The class `BaleOfTurtles` (bale being the collective noun for turtules) would want to implement `IEnumerable` and `IEnumerable`. A turtle is not an animal but a reptile but it does have 4 limbs used for locomotion. How would you go about sorting this mess out? – Ben Oct 21 '11 at 18:04
  • 4
    @Ben: Most of the time you see this sort of thing is because someone is trying to emulate generic covariance. Now that we have it in the language, you don't need to pull shenanigans like this. If `Giraffe` implements `IAnimal` and `IQuadruped`, then `IEnumerable` is automatically convertible to `IEnumerable` and `IEnumerable`, so *the collection needs only to implement `IEnumerable`*. Let the covariance system take care of the conversions for you, rather than implementing the interfaces separately. – Eric Lippert Oct 21 '11 at 18:25
  • 12
    Also, I think you'll find that turtles are animals. – Eric Lippert Oct 21 '11 at 18:25
12

A cat is not a sequence of legs, eyes, and whiskers. Rather, it has a sequence of legs, eyes and whiskers. Composition over inheritance.

Instead of having ComponentModel be thought of as two completely unrelated sequences of IComponentA and IComponentB, you should remove this and just add methods:

public IEnumerable<IComponentA> GetSequenceOfComponentA() { // }
public IEnumerable<IComponentB> GetSequenceOfComponentB() { // }

(What do you even expect foreach(var x in componentModel) { // } to do? What happens here: public void M(IEnumerable<IComponentA> a) { } and public void M(IEnumerable<IComponentB> b) { } and then M(componentModel)?)

jason
  • 236,483
  • 35
  • 423
  • 525
  • Thanks Jason but I am a bit confused by your answer. Do you mean that your cat would have an object called SequenceOfLegs? What do you mean by "you should just remove this"? Interface A and B are not quite unrelated - if interface A was a cat's leg then interface B could be a cat's rear leg. It was my idea (perhaps a bad idea) that when a leg is added to the cat the model class will check if it is a rear leg and add it to either list A or to list A and B. I am not sure what I expected the foreach(var x in componentModel) to do, I guess I am going about this wrong. – Ben Oct 21 '11 at 15:31
  • 2
    @Ben: Remove that `ComponentModel` implements `IEnumerable` and `IEnumerable`. When you have a class that implements `IEnumerable`, you're saying that any instance of the class *is* a sequence of `T`. By implementing both `IEnumerable` and `IEnumerable` you're saying that it *is* a sequence of `IComponentA` and a sequence of `IComponentB`. That doesn't make sense. The natural numbers are not a sequence of odd numbers and a sequence of even numbers. It makes more sense to say it *has* sequences of `IComponentA`s and `IComponentB`s. – jason Oct 21 '11 at 15:51
  • Ah great I understand now - thanks for your help Jason. All the lessons about "if you can say - is a - then its inheritance or - has a - then its composition" seem to be coming back to me now. Using the solution offered by James seems to conform to your lesson here so I will use it, but thanks for your help also. – Ben Oct 21 '11 at 16:13
0

maybe something along these lines would work. it does a public class MyCollection(T) : IEnumerable(T) to use the same type to handle 2 different types of data

you could go further with MyCollection(T,X,Y,Z) : IEnumerable(T) where X,Y,Z are lists of your other types except that the T would be your master iterator running internally iterating your other lists in parallel.

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Start.....");
        for ( int i = 0; i  < 10; i++)
        {
            IEnumerable collection;

            Console.WriteLine();

            if (i % 2 == 0)
            { Console.Write("Ints..... ");  
              collection = new MyCollection<int>(new int[] { 1,2,3 });  }
            else
            { Console.Write("Strings..... ");  
              collection = new MyCollection<string>(new string[] { "x","y","z" } ); }

            foreach (var item in collection) { Console.Write(item); }
            Console.WriteLine();
        }
        Console.WriteLine(); Console.WriteLine("End....."); Console.ReadLine();
    }
}

public class MyCollection<T> : IEnumerable<T>
{
    private T[] _Tdata;
    public MyCollection4(T[] arrayOfT)
    {
        _Tdata = arrayOfT;
    }

    public IEnumerator<T> GetEnumerator() 
    {

        var listofT = new List<T>(_Tdata);
        return listofT.GetEnumerator();

    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
Juan Suero
  • 33
  • 1
  • 5