From the book:
1) int i = 7;
2) Object o = i; // Implicit boxing int-->Object
3) Object[] a3 = new int[] { 1, 2 }; // Illegal: no array conversion
The assignments in 3) is illegal
because int is not a reference type
and so int[] is not implicitly
convertible to Object[]
I don’t get this . on line 2) it shows that int is implicitly convertible to Object, and in the third line, it says int[] is not implicitly convertable. wha ??
Not to restate the problem, but it’s because
int[]is not implicitly (or explicitly, for that matter) convertible toObject[].Arrays are types in and of themselves.
int[]simply means “a series ofintvariables”, just likeObject[]means “a series ofObjectvariables”.Incidentally, all arrays are reference types, it’s just that
int[]is a reference type representing a series of a particular value type.EDIT
Don’t allow the talk about covariance to confuse you. This is a widely misunderstood topic, and one that’s not really beneficial for a beginning developer to try to tackle. Yes, .NET 4.0 introduces the ability to specify an operation as being covariant or contravariant, but that won’t allow for assignment compatibility between incompatible types like
Object[]andint[]. Consider the following example, assuming that it would compile.Now we have a problem. If it were legal to assign an
int[]to anObject[], then I now suddenly (magically) have astringvalue in myint[]array–something that should never happen, and actually can’t happen, since anintvariable cannot hold astringvalue.Others have (correctly) pointed out that something like this does compile:
I’ll leave it to someone like Eric Lippert to explain why this sort of operation works (it’s essentially assuming covariance when it isn’t necessarily the case) [EDIT: Thanks to Tim Goodman, who actually posts Eric’s explanation, or at least statement, about this], but fundamentally any reference type is technically capable of holding a reference to any type. In other words, when I declare a
stringvariable it allocates the same amount of memory (for the variable) as if I were to declare aDbConnectionvariable; they’re both reference types. For value types, the amount of memory allocated depends on the type, and they are fundamentally incompatible.You will note, however, that you will get a runtime exception (
ArrayTypeMismatchException) when performing the last step (assigning anintto the second array element), since the underlying array is actually astring[].