8

Why is this legal,

string[] arr = new string[5];
Object[] arr2 = arr;

But this is a compile-time error,

int[] arr = new int[5];
Object[] arr2 = arr;

Aren't int and string both derived from Object? Is it a ValueType thing? If so, why is it this way?

5
  • I believe the answer is that a String is not a primitive type, whereas an int is a primitive type. Commented Jul 9, 2013 at 16:13
  • Value type is the correct word I believe.. doing this with Int32 still yields compile error. Commented Jul 9, 2013 at 17:28
  • Erm... I don't think Int32 is any different? Isn't "int" and "float" just the C# keyword, but Int32 and Int64 the "CLR" erm -- identifier -- for them? :) Commented Jul 9, 2013 at 18:29
  • But yeah, you may be right on the name part. I know that int, float, char, etc. are primitives, but value vs. reference type is more relevant to the discussion. Commented Jul 9, 2013 at 18:30
  • @aikeru Oops, sorry I was thinking Int32 wasn't primitive. So enum, decimal, and struct are the only value types that are not primitive. Commented Jul 10, 2013 at 1:24

2 Answers 2

7

The C# language only provides covariance for arrays of reference types. This is documented on MSDN:

For any two reference-types A and B, if an implicit reference conversion (Section 6.1.4) or explicit reference conversion (Section 6.2.3) exists from A to B, then the same reference conversion also exists from the array type A[R] to the array type B[R], where R is any given rank-specifier (but the same for both array types). This relationship is known as array covariance.

In your second example, you're using an array of System.Int32 types, which are not reference types, so the array covariance support does not apply. Reference types are, at their core, all storing an array of references, where the references are all an identical size. Value types can be any size, so there is no guarantee that the array elements would be the same size, which prevents this from working properly.

Sign up to request clarification or add additional context in comments.

Comments

4

This is called unsafe array covariance.

It only works for arrays of reference types.

Arrays of value types are a physically different size, so this cannot work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.