Roman Koliada
Roman Koliada

Reputation: 5082

ToList<T>() vs ToList()

Does it make sense to specify a concrete type in ToList<T>(), AsEnumerable<T>(), etc methods?

Will .ToList<SomeClass>() execute faster than just .ToList()?

Upvotes: 2

Views: 2250

Answers (2)

Jakub Lortz
Jakub Lortz

Reputation: 14896

It's the same method

public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source);

The type parameter can be inferred by the compiler, so you don't need to specify it (unless you need a List of different type than the IEnumerable - in that case you need to specify the type explicitly).

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1500065

It makes sense if the compiler infers one type and you want to specify another. It doesn't make sense otherwise.

For example, suppose you have an IEnumerable<string> and want to create a List<T>... if you want a List<string> then just call ToList(). If you want to use generic covariance and get a List<object>, call ToList<object>:

IEnumerable<string> strings = new [] { "foo" };
List<string> stringList = strings.ToList();
List<object> objectList = strings.ToList<object>();

The generated IL for the middle line will be the same whether you use the above code or

List<string> stringList = strings.ToList<string>();

It's just a matter of the compiler inferring the type for you.

Will .ToList<SomeClass>() execute faster than just .ToList()?

No, due to the above... the same code is generated.

Upvotes: 13

Related Questions