The difference between ToArray () and ToArray <int> ();

Sorry if I ask a stupid question, but can someone explain the difference between the next two calls ( ToArray ). In intellisense, it does not show them as overloaded methods, and, of course, the output of both calls is the 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>(); 
+6
source share
5 answers

There is no difference. In the first call, the compiler deduced the int type, and in the second, explicitly.

There may be times when a type is needed because it cannot be inferred. For example, you have a custom collection that implements IEnumerable<T> twice, for two different types of T This impairs usability, so it is preferable to avoid such structures.

+5
source

It makes no difference, this is exactly the same ToArray () method. The compiler can simply conclude that you need a version of ToArray<int> from the expression syntax. The return value of Where () was output to return an int. In other words, it uses Where<int>() . This was inferred from the List <> type. Therefore, he can conclude that you need a ToArray<int> .

Thus, the type type chain is List<int> => Where<int>() => ToArray<int>() .

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

+5
source

This is the same general method. In the first case, the generic type parameter is inferred by the compiler from the parameter of the general enumeration type, which you call ToArray<T>() on. But you can also specify it explicitly.

+4
source

It is the same. You are witnessing what is called a "type of inference." In some scenarios, the C # compiler can detect the type based on the passed parameters, and you do not need to explicitly specify the type parameters. In your example, it is known that i is an IEnumerable<int> , and therefore .ToArray() can output an int parameter.

Here is a good article that goes into this: http://joelabrahamsson.com/a-neat-little-type-inference-trick-with-c/

+3
source

There are no differences.

 int[] input = i.Where(j => j % 2 == 1).ToArray(); 

Here, only the compiler outputs the general argument T , based on the type of the enumerated call ToArray() on.

 input = i.Where(j => j % 2 == 1).ToArray<int>(); 

Here, the return value of Where() is output by the compiler to return an int .

  • ToArray<T>() is generic, so it can work on any IEnumerable<T> .
  • ToArray() actually just redirects to an implicit interpretation of ToArray<T>() based on the T original IEnumerable.
  • If you call the general method and do not specify any type arguments, the compiler will try to print them for you.
+2
source

Source: https://habr.com/ru/post/947067/


All Articles