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

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow