Why can't the compiler infer the type of an array of objects?

I am wondering why this is really:

object[] array = {"bla bla bla..", 23, true};

But this is not so:

var array = {"bla bla bla..", 23, true };
var array2 = new [] {"bla bla bla..", 23, true };

In the second example, why the compiler cannot infer the type of the array according to the values ​​in the array initializer? This seems very easy to use, especially compared to the typical output type. To define an array of objects, why should I explicitly specify the type of array?

var array = new object[] { "bla bla bla..", 23, true };
+4
source share
3 answers

Since the types in the array are not concrete object, they are 3 different types, which are all subclasses of the object.

, , . , :

var arr = new[] {3, 4, 5}; // Will correctly infer int[]

, 8.5.1 #, , var :

  • .
  • - .
  • .
  • .

:

var y = {1, 2, 3};   // Error, array initializer not permitted

new [] {"bla bla bla..", 23, true };, 7.6.10. , :

var d = new[] { 1, "one", 2, "two" }; // Error

, , :

, int, , . , , , []. , ,

+6

, . , , object.

: , : ( int)

var array = {1, 2, 3, 4, 5, "6", 7, 8, 9};

"6" . , , object[], , int[].

Python - , .

+2

Microsoft

[...]. , . , .

: CS0826

+1

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


All Articles