Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting int array to object array

Tags:

c#-4.0

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?

like image 869
countunique Avatar asked Jul 09 '13 16:07

countunique


People also ask

How do you cast an array to an object?

To convert an array into an object we will create a function and give it 2 properties, an array and a key. const convertArrayToObject = (array, key) => {}; We will then reduce the array, and create a unique property for each item based on the key we have passed in.

Can we assign Integer array to object array C#?

It only works for arrays of reference types. Arrays of value types are a physically different size, so this cannot work.

Can you cast an int array to Integer array?

We can use Java 8 Stream to convert a primitive integer array to Integer array: Convert the specified primitive array to a sequential Stream using Arrays. stream() . Box each element of the stream to an Integer using IntStream.

How do you convert an array to an object in java?

Converting an array to Set object The Arrays class of the java. util package provides a method known as asList(). This method accepts an array as an argument and, returns a List object. Use this method to convert an array to Set.


2 Answers

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.

like image 149
Reed Copsey Avatar answered Sep 27 '22 21:09

Reed Copsey


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.

like image 30
SLaks Avatar answered Sep 27 '22 21:09

SLaks