namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
object[] obj = new object[3];
obj[0] = new object();
obj[1] = "some string";
obj[2] = 10;
string[] strings = new string[] { "one", "two", "three" };
obj = strings; //---> No Error here, Why ?
int[] ints = new int[] { 1, 2, 3 };
obj = ints; /*-> Compiler error - Cannot implicitly convert type 'int[]' to 'object[]', Why ?*/
}
}
}
I get a compiler error while doing the step as shown above. But, in the preceding step, there is no error. Can somebody explain me this behavior ? I am using VS 2010.
EDIT – For sake of completeness, again, this won’t compile – Variance support in .NET 4.0 has been cleaned up now. One can use new keywords in and out with generic type parameters.
List<object> objectList = new List<object>();
List<string> stringList = new List<string>();
objectList = stringList;
Only arrays of reference types (like
String) may be assignable to arrays of other reference types (likeObject). Sinceintis a value type, arrays of it may not be assigned to arrays of other types.To be more specific, this is called array covariance. It only works when the bit patterns stored in the array are compatible with the destination type. For example, the bits in a
String[]are all references to strings and can be safely copied into memory locations storing references to objects. An array of value types, however, stores the actual data of the elements (as opposed to just references to them). This means that anint[]stores the actual 32-bit integers in the elements of the array. Since a 32-bit integer cannot be safely copied into a memory location storing a reference to an object or any other type, you cannot assign an array of them to an array of any other type.Note that technically the bits of an
intcan be safely copied into a memory location storing auint(and vice-versa). This means that you should be able to do something likeint[] x = new uint[10]. This is not actually covariance and C# does not allow it. However, it is legal in the CLR and you can convince C# to let you do it if you want to.