Question

As C# compiler can implicitly convert type 'char' to 'int', I expected it to also implictly convert type 'char[]' to 'int[]'.

However, the following code returns compile-time error CS0029 Cannot explicitly convert type 'char[]' to 'int[]'.

int[][] jaggedArray = new int[][]
{
  new[]{'a'},
  new[]{1}
};

Is there a technical reason why this conversion can't be provided ?

Was it helpful?

Solution

It's just the way the language is defined. C# could have been defined to automatically create a new array from the old one and convert the elements item-wise. Of course, that would create an independent array. Mutations of one of the arrays would not propagate to the other. This is confusing to the developer. That's probably why C# does not do that.

In any case an int[] cannot be treated as a char[] because the two have incompatible memory layouts. A reinterpretation of the bits is not enough to perform the conversion.

This question has nothing to do with jagged arrays. This issue can be captured completely with two variables of types int[] and char[]. This makes the issue easier to understand.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top