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>();
                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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With