![]() ![]() | introductory-examples/array-string-types/ex.cs - A demonstrations of arrays in C#. | Lecture 0 - slide 7 : 25 Program 1 |
public static void ArrayDemo(){ string[] a1; // a1 is uninitialized string[] a2 = new string[3]; // an array with three null values string[] a3 = {"a", "bb", "ccc"}; // an array with 3 strings string[] a4 = new string[]{"a", "bb", "ccc"}; // equivalent string[] a5 = new string[3]{"a", "bb", "ccc"}; // equivalent // string[] a6 = new string[2]{"c", "b", "a"}; // Compile time error // 'Invalid rank specifier'. Not space enough in array. Omit [2] // a1 is assigned to a new string array. a1 = new string[]{"a", "bb", "ccc"}; int[,] b1 = new int[2,4]; // 2 rows, 4 columns // all initialized to default(int) int[,] b2 = {{1,2,3,4}, {5,6,7,8}}; int[,] b3 = new int[2,4]{{1,2,3,4}, {5,6,7,8}}; // equivalent // int[,] b4 = new int[3,4]{{1,2,3,4}, {5,6,7,8}}; // Compile time error // 'Invalid rank specifier'. Add a third row. // b1 is assigned to a new int arrays. 2 rows, 4 columns b1 = new int[,]{{1,2}, {3,4}, {5,6}, {7,8} }; double[][] c1 = { new double[]{1.1, 2.2}, new double[]{3.3, 4.4, 5.5, 6.6} }; Console.WriteLine("Array lengths. a1:{0} b3:{1} c1:{2}", a1.Length, b3.Length, c1.Length); // 3, 8, 2 Array.Clear(a2,0,3); // Set a[0], a[1], a[2] to default values Console.WriteLine("Length of a3: {0}", a3.Length); // 3 Array.Resize<string>(ref a3,10); Console.WriteLine("Lenght of a3: {0}", a3.Length); // 10 Console.WriteLine("Ranks of b1 and c1: {0}, {1}", b1.Rank, c1.Rank); // 2, 1 Console.WriteLine("Sorting:"); Array.Sort(a5); foreach(string str in a5) Console.WriteLine(str); }