Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ToArray() & ToArray<int>();

Tags:

c#

.net

Excuse me if I am asking silly question, but can anybody explain the difference between following two calls (ToArray). In the intellisense it does not show them as overloaded methods & of course the output of both the calls are same.

List<int> i = new List<int> { 1, 2, 5, 64 };
int[] input = i.Where(j => j % 2 == 1).ToArray();
input = i.Where(j => j % 2 == 1).ToArray<int>();
like image 782
Atul Sureka Avatar asked Jun 12 '13 01:06

Atul Sureka


2 Answers

There is no difference, it is the exact same ToArray() method. The compiler can simply infer that you want the ToArray<int> version from the syntax of the expression. The return value of Where() was inferred to return int. In other words, it uses Where<int>(). Which was inferred from the type of the List<>. So it can infer that you need ToArray<int>.

So the type inference chain is List<int> => Where<int>() => ToArray<int>().

Change the list to, say, List<long> and the expression still works without having to modify it.

like image 116
Hans Passant Avatar answered Nov 09 '22 04:11

Hans Passant


There is no difference here. In the first call, the compiler has inferred the type int, while in the second you have specified it explicitly.

There may be cases where the type is necessary because it cannot be inferred. For example, you have a custom collection that implements IEnumerable<T> twice, for two different types T. This hurts usability so it is preferable that you avoid such constructions.

like image 22
Mike Zboray Avatar answered Nov 09 '22 04:11

Mike Zboray