1

I've used GroupBy(), and produced an IEnumerable<IGrouping<TKey,TValue>>.

And I can foreach over it, and pass each element (each IGrouping<TKey,TValue>) into a method that accepts IEnumerable<TValue>

This is unsurprising - IGrouping<TKey,TValue> implements IEnumerable<TValue>

But if I define a method that accepts IEnumerable<IEnumerable<B>>, then I can't directly pass in the output of GroupBy(), even though it is an IEnumerable<> and every element inside it is an IEnumerable<B>

Why?

Brondahl
  • 7,402
  • 5
  • 45
  • 74
  • It works for me. Post the exact method signature and how you're calling it. My guess is your `B` doesn't match `TValue`. – D Stanley Jul 17 '14 at 15:14
  • 3
    `IEnumerable` is covariant, so it should work. See this [fiddle](https://dotnetfiddle.net/mkSSXz). – dcastro Jul 17 '14 at 15:37
  • 3
    Covariance/Contraviance was introduced into C#4. Hence if you are compiling in VS2008, this would not work. – Aron Jul 17 '14 at 17:42
  • Ah, yes, I'm compiling against .NET 3.5 I knew vaguely that covariance was relevant to this, but I thought that what was added in C#4 was the ability to control it in your own generic classes, hadn't realised that framework classes couldn't do it before then either. Thanks! – Brondahl Jul 17 '14 at 20:22
  • @Aron or Brondahl make it an answer, making this a proper question. – nawfal Jul 22 '14 at 16:12

1 Answers1

0

As pointed out by several people (and indeed, as I sort of knew in the back of my head) this is simply a covariance issue, and only breaks in a pre-.NET 4 environment.

Brondahl
  • 7,402
  • 5
  • 45
  • 74