01 nums binary-long occurs 3 values 1, 2, 3. *> reference single-dimensional array 01 names1 string occurs 5. *> 5 is the size of the array 01 names2 string occurs any. *> size of array deferred until run-time 01 names3 string occurs 7. 01 names4 string occurs any. 01 twoD float-short occurs any, any. *> 2-dimensional (rectangular) array 01 jagged binary-long occurs any, occurs any. *> 2-dimensional (jagged) array 01 rows binary-short value 4. 01 cols binary-short value 3. procedure division. *> another way to reference an array set content of nums to (1, 2, 3) *> another way to set size of array set size of names1 to 5 set names1(1) to "Rod" *> first element indexed as 1 set names1(6) to "Jane" *> throws System.IndexOutOfRangeException *> resizing arrays *> resizes array by assigning reference to new array - current contents are lost to the garbage collector set size of names1 to 10 *> to retain existing values, copy the array into a new array of the required size invoke type Array::Copy(names1, names3, size of names3) *> copies array, maintaining its contents *> or: invoke type Array::Resize(names1,10) *> resizes array, retaining existing index values *> or: set size of names4 to size of names1 invoke names1::CopyTo(names4, 0) *> 2-dimensional arrays set size of twoD to rows, cols set size of jagged to 3 set size of jagged(1) to 5 set jagged(1 5) to 5
int[] nums = {1, 2, 3}; for (int i = 0; i < nums.Length; i++) { Console.WriteLine(nums[i]); } // 5 is the size of the array string[] names = new string[5]; names[0] = "Rod"; names[5] = "Jane"; // Throws System.IndexOutOfRangeException // C# can't dynamically resize an array. Just copy into new array. string[] names2 = new string[7]; // or names.CopyTo(names2, 0); Array.Copy(names, names2, names.Length); float[,] twoD = new float[rows, cols]; twoD[2,0] = 4.5f; int[][] jagged = new int[3][] { new int[5], new int[2], new int[3] }; jagged[0][4] = 5;
Portions of these examples were produced by Dr. Frank McCown, Harding University Computer Science Dept, and are licensed under a Creative Commons License.