C# in Depth

Cover of C# in Depth
Order now (3rd edition)

MakeList revisited

Chapter 3: Parameterized typing with generics: 3.2.3

Created: 1/28/2008
Last updated: 1/28/2008

The MakeList method of listing 3.3 accomplishes its aim of helping to teach about generic methods, type inference etc. However, for real life use you might want consider this alternative:

static List<T> MakeList<T> (params T[] elements)
{
    return new List<T>(elements);
}

Despite being so short, this is still useful - because you can use type inference to avoid actually having to specify T in the calling code. This can be very useful in some cases. An alternative might help you to work round the lack of generic covariance:

static List<TResult> MakeList<TSource,TResult> (params TSource[] elements)
    where TSource : TResult
{
    List<TResult> ret = new List<TResult>(elements.Length);
    foreach (TResult t in elements)
    {
        ret.Add(t);
    }
    return ret;
}

Of course you then need to specify the types - but through the wonders of overloading by the number of type parameters, you can actually have both methods at the same time. Of course, the ToList and Cast extensions methods in LINQ to Objects make this somewhat less important if you're using .NET 3.5...