2010-03-30 Jb Evain <jbevain@novell.com>
[mcs.git] / docs / ecma334 / 19.5.xml
blob697196d495c1947ce7cc57a7128ee72eee9ad0ba
1 <?xml version="1.0"?>
2 <clause number="19.5" title="Array covariance">
3   <paragraph>For any two <non_terminal where="11.2">reference-type</non_terminal>s A and B, if an implicit reference conversion (<hyperlink>13.1.4</hyperlink>) or explicit reference conversion (<hyperlink>13.2.3</hyperlink>) 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 <non_terminal where="19.1">rank-specifier</non_terminal> (but the same for both array types). This relationship is known as array covariance. Array covariance, in particular, means that a value of an array type A[R] may actually be a reference to an instance of an array type B[R], provided an implicit reference conversion exists from B to A. </paragraph>
4   <paragraph>Because of array covariance, assignments to elements of reference type arrays include a run-time check which ensures that the value being assigned to the array element is actually of a permitted type (<hyperlink>14.13.1</hyperlink>). </paragraph>
5   <paragraph>
6     <example>[Example: For example: <code_example><![CDATA[
7 class Test  
8 {  
9    static void Fill(object[] array, int index, int count, object value) {  
10       for (int i = index; i < index + count; i++) array[i] = value;  
11    }  
12    static void Main() {  
13       string[] strings = new string[100];  
14       Fill(strings, 0, 100, "Undefined");  
15       Fill(strings, 0, 10, null);  
16       Fill(strings, 90, 10, 0);  
17    }  
18 }  
19 ]]></code_example></example>
20   </paragraph>
21   <paragraph>
22     <example>The assignment to array[i] in the Fill method implicitly includes a run-time check, which ensures that the object referenced by value is either null or an instance of a type that is compatible with the actual element type of array. In Main, the first two invocations of Fill succeed, but the third invocation causes a System.ArrayTypeMismatchException to be thrown upon executing the first assignment to array[i]. The exception occurs because a boxed <keyword>int</keyword> cannot be stored in a string array. end example]</example>
23   </paragraph>
24   <paragraph>Array covariance specifically does not extend to arrays of <non_terminal where="11.1">value-type</non_terminal>s. For example, no conversion exists that permits an int[] to be treated as an object[]. </paragraph>
25 </clause>