I'm in a dilemma to choose the return type of collections when writing generic extension methods for an API. I have read discussions on SO on what collection type to return and what should be the design choices. I generally prefer to accept the most basic type as argument and return the richest type.
I'm now thinking of returning the same type that is provided with. Irrespective of whether this is a good choice or not, is there a way this can be accomplished in an easy to use manner?
For eg. lets I have this:
public static IEnumerable<T> Generize<T>(this IEnumerable<T> source)
where T : new()
{
var lst = source.ToList();
lst.Add(new T());
return lst.AsEnumerable(); //since return type is IEnumerable.
}
Now I want to return an IEnumerable, ICollection or IList depending on the argument source. So I modified this a bit.
public static S Generize<S, T>(this S source) where S : IEnumerable<T>
where T : new()
{
var lst = source.ToList();
lst.Add(new T());
return (S)lst.AsEnumerable(); //not sure if this works
}
The main problem I'm facing is I can't get to call the function Generize.
var d = new List<int> { 23, 23 };
d.Generize(); //can not find definition and no extension method by the name.....
d.Generize<List<int>, int>(); //works but so ugly..
As Marc points out the casting doesn't work everywhere. Is there a better way to return a collection of type
Sfrom aList<T>ifSis anyway aIEnumerable<T>?Can it be done without specifying types such that types are inferred automatically?
Also why is
d.Generize()givingdefinition not founderror rather thantypes cannot be inferrederror?
Edit:
Though IEnumberable<T> can be of any concrete type, in my case it would have been only the normally found ones like T[] or List<T> or few more from Linq namsespace. Handling them all wont be easy. Just pointing out that the original question doesn't make sense to me now. Thanks all..!