byte b =10;
int a = b; // Primitive data type widening
// Works perfectly fine
the above code will give no error/warnings. But why is the same not applicable for the below mentioned code?
byte[] b = new byte[10];
int[] i1 = b; //Cannot convert from byte[] to int[]
int[] i2 = new byte[10]; //Cannot convert from byte[] to int[]
my question is, since int can hold any and all byte values, why is this not the case with arrays?
they are both holding the addresses afterall. And this would be upcasting if this was possible for ref variables.
The array created by
new byte[10]
can contain 10byte
values. If you were able to assign it to a variable of typeint[]
, the compiler would assume (mistakenly) that your array ofbyte
s can contain 10int
values.Consider the following code, which is invalid:
and the following code, which is valid:
If
int[] i2 = new byte[10];
was valid, the compiler would have allowed you to store anint
in a variable of typebyte
.The language spec defines subtyping between array types in Sec 4.10.3:
The final bullets ("If
P
is a primitive type...") show that the language does not define any relationship between arrays of differing primitive types. The only valid assignments are:This doesn't provide an answer as to why it is like this; you'd have to ask the language designers. However, simple examples like that shown by Eran demonstrate why it would not be safe to do as OP proposes.
It should be noted that the first line - which permits an assignment like
was a design error: that arrays are covariant makes them not type safe. This is one reason to strongly prefer generics to arrays, since generics are invariant, and so prevent such assignments.