Hello everyone,
Array in C# is co-variant implicitly on reference type:
object[] listString = new string[] { "string1", "string2" };
But not on value type, so if you change string to int, you will get compiled error:
object[] listInt = new int[] {0, 1}; // compile error
Now, the concern is when you declare int
array like two syntaxes below which do not explicitly declare the type int
, just only differentiate on new[]
, compiler will treat differently:
object[] list1 = { 0, 1 }; //compile successfully
object[] list2 = new[] {0, 1}; //compile error
You will get object[] list1 = { 0, 1 };
compiled successfully, butobject[] list2= new[] {0, 1};
compiled error.
It seems the C# compiler treats
object[] list1 = { 0, 1 };
as
object[] list1 = new object[]{ 0, 1 };
but
object[] list2 = new[] { 0, 1 };
as
object[] list2 = new int[]{ 0, 1 }; //error because of co-variant
Why C# compiler behaves in the different way on this case?
The version that compiles uses an array initializer to initialize
list1
. The C# language spec, §1.110 ("Array initializers") states:So it is obvious that this should compile.
The second version uses an explicit array creation expression, where you instruct the compiler specifically what type of array to create. §1.51.10.4 ("Array creation expressions") states:
Therefore, the second version is equivalent to
So the question now effectively becomes "why can I not assign an int[] to an object[]", just as you mention at the end of the question. And the answer is also simple, given in §1.109 ("Array covariance"):