I wrote this extension method (which compiles):
public static IEnumerable<J> Flatten<T, J>(this IEnumerable<T> @this)
where T : IEnumerable<J>
{
foreach (T t in @this)
foreach (J j in t)
yield return j;
}
The code below causes a compile time error (no suitable method found), why?:
IEnumerable<IEnumerable<int>> foo = new int[2][];
var bar = foo.Flatten();
If I implement the extension like below, I get no compile time error:
public static IEnumerable<J> Flatten<J>(this IEnumerable<IEnumerable<J>> @this)
{
foreach (IEnumerable<J> js in @this)
foreach (J j in js)
yield return j;
}
Edit(2): This question I consider answered, but it raised another question regarding overload resolution and type constraints. This question I put here: Why aren't type constraints part of the method signature?
foo.Flatten<IEnumerable<int>, int>();
should work. – Permeate