Reputation: 205
I have the following method
private void AM(object[] x)
{
}
When we call it like this:
int[] x = new int[1];
AM(x);
We get a compilation error, something like "invalid arguments", "cannot convert from int[] to object[]".
But, if we have an argument (object y), we can have input int as input parameter.
My question is: why Microsoft design them in different ways?
Upvotes: 4
Views: 5210
Reputation: 17724
Only arrays of reference types may be assigned to arrays of other reference types (like Object). Since int is a value type, you can't do this.
This is called Array Covariance
Array covariance specifically does not extend to arrays of value-types. For example, no conversion exists that permits an int[] to be treated as an object[].
Upvotes: 5
Reputation: 32586
When you pass an int
(a value type) into a method with an object
(a reference type) parameter, a new object is created on the heap and the value of the int
is copied into it. A reference to the object (the boxed int
) is then given passed into the method parameter.
int[]
and object[]
are both arrays, but they have very different element types. As arrays, they are both reference types, and so a method taking an object[]
parameter is expecting a reference to an array of objects. A reference to an array of ints is very different.
Because int
is a value type, there's no simple way to turn a reference to int[]
into a reference to object[]
without iterating over the whole int[]
and boxing each element. That could be an expensive operation in terms of time and memory, and the compiler is not going to do it for you automatically.
Upvotes: 10
Reputation: 3317
An array of objects is a completely different animal when compared to an array of int (as you can see with the cast error you get). However, both object[] and int[] are objects, so you can cast them both to their primal type (as in primitive) which is the object.
Upvotes: 2