How can I create a generic method so the return type is either a list or an array?
Now for this method I get this error:
(string, int)[]’ must be a non-abstract type with a public
parameterless constructor in order to use it as parameter ‘T’ in the
generic method ‘T TournamentsAnalytics.GetParameters()
private void Test()
{
var parameters = GetParameters<List<(string, int )>>();
var parameters2 = GetParameters<(string, int)[]>();
}
private T GetParameters<T>() where T: ICollection<(string, int)>, new()
{
var parameters = new T
{
("nr1", 1),
("nr2", 2),
("nr3", 3),
("nr4", 4),
("nr5", 5),
("nr6", 6)
};
return parameters;
}
>Solution :
You probably should not use generics for this. You could for example just use LINQ to convert a sequence of values to a list or an array:
GetParameters().ToList();
GetParameters().ToArray();
...
private IEnumerable<(string, int)> GetParameters(){
yield return ("nr1", 1);
yield return ("nr2", 2);
...
This seem like it is both much shorter and simpler than messing around with generics. Or just return either a list or an array, and use LINQ to convert to the other type if needed, for small lists created infrequently any inefficiencies will be irrelevant.
There might be ways to use generics if you have some specific issue to solve, For example delegating the creation of the collection to the caller by injecting a delegate: Func<IEnumerable<(string, int)>, T), but it will likely just make things more complicated.
Note that your example uses a collection initializer, and this will just not work with arrays, since this initializer uses the Add-method, and this will just not work for arrays.