Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a generic method for list and array

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading