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?