xdevel2000
xdevel2000

Reputation: 21364

Implicit reference conversions between array type

In C# standard is written that exsists an implicit conversion between array according to the following rules:

From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true:

but if I make:

int[] j = { 1, 2 };
int[] k = { 1 };

k = j;

no compiler error is emitted. Maybe I didn't understand the meaning of this rule...

but, again, in the example above the element type of j and k are value types.

here if I have:

int[] j = { 1, 2 };
short[] k = { 1, 5 };

j = k;

it seems like there can be an implicit conversion from element of type short to element of type int but the complier not compile. Emit an error.

Sincerely I can't figure how this rule work!

Upvotes: 0

Views: 114

Answers (4)

Ahmed Anwar
Ahmed Anwar

Reputation: 678

What this code does is that it makes both k and j point to the same array, { 1, 2 }

since both k and j are arrays with the same number of dimentions and the same element type, you can make one point to the other using this code

Upvotes: 1

AustinWBryan
AustinWBryan

Reputation: 3326

S and T refer to the type of the arrays. In which case, j and k are both type int[] so there is no implicit conversion because they are the same type.

Since they don't differ in element type, their dimensions are irrelevant.

Upvotes: 0

Vadim Martynov
Vadim Martynov

Reputation: 8892

  1. Your arrays has the same element types.
  2. Your arrays has value types in their elements.
  3. Your arrays has the same dimentions - one.
  4. Multi-dimensional arrays looks like this: int[,,] (3 dimentions).

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156968

Both j and k are the same type. There are both an integer array, and they both have one dimension. So the array is entirely according to the rules.

These are the incorrect usings of the arrays as described in the documentation:

object[] j; int[] k;

int[,] j; int[] k;

float[] j; int[] k;

Upvotes: 2

Related Questions