Suppose you have a list class like
class Words : List<Word>
{
...
}
and suppose you want to create one of these from an IEnumerable<Word>
with a function like:
public static TList ToTypedList<TList, T>(this IEnumerable<T> list)
where TList : IList<T>, new()
{
var listTyped = new TList();
foreach (var item in list)
{
listTyped.Add(item);
}
return listTyped;
}
so that you can write:
Words words = someEnumerableOfWords.ToTypedList<Words, Word>();
It seems redundant to have to specify the Word
type parameter, since someEnumerableOfWords
is already of type IEnumerable<Word>
and could be inferred, but doing, say, this:
Words words = someEnumerableOfWords.ToTypedList<Words>();
causes a compiler error.
Is there any way to accomplish the kind of type inference that I'm looking for?
Update: To clarify why I want to do this, it's not just about saving a few characters while typing, but also have a chainable, fluid interface:
var result = object.Child.MethodThatOutputsWords().ToTypedList<Words>().DoSomethingWithTheWords().DoSomethingElse();
The suggestion to just make another constructor that takes the list of words isn't perfect because it would require
var result = new Words(object.Child.MethodThatOutputsWords()).DoSomethingWithTheWords().DoSomethingElse();
and I find that much harder to read, because you can't just scan left to right, as in the first example.