Jamie Brown
Jamie Brown
CC#
Created by Jamie Brown on 9/17/2024 in #help
✅ Can't infer type arguments from usage
I was looking into writing an extension method to Flatten nested collections, as I always forget that SelectMany(i => i) exists (and also personally think it's ugly/non-intuitive). Said method looks like so:
public static IEnumerable<TValue> Flatten<TOuter, TInner, TValue>(this TOuter items) where TOuter : IEnumerable<TInner> where TInner : IEnumerable<TValue>
{
return items.SelectMany(item => item);
}
public static IEnumerable<TValue> Flatten<TOuter, TInner, TValue>(this TOuter items) where TOuter : IEnumerable<TInner> where TInner : IEnumerable<TValue>
{
return items.SelectMany(item => item);
}
Which is all fine and dandy, but if I go to use this like so:
List<List<int>> thing = [];
thing.Flatten();
List<List<int>> thing = [];
thing.Flatten();
The compiler will complain about being unable to infer the type arguments, so now I'd have to write this like so:
List<List<int>> thing = [];
thing.Flatten<List<List<int>>, List<int>, int>();
List<List<int>> thing = [];
thing.Flatten<List<List<int>>, List<int>, int>();
Which is even more hideous, and unintuitive to use than our good friend SelectMany() was in the first place. Is there a way (missing a constraint maybe?) to have this work without specifying the generic parameters? And if not why? It seems like the sort of thing that shouldn't be too difficult to reason about, but maybe this is another case where the brain is able to jump through hoops and connections the compiler is unable to.
10 replies