Rectangular arrays are, as the name implies, arrays which look like a table. A 2D rectangular array can be represented as a plane rectangle, and a 3D rectangular array can be represented as a cuboid. [4] Whatever the case, the idea is the same “ in rectangular arrays, every row has the same number of columns . Jagged arrays differ from this as you will see later.
The syntax for rectangular arrays is different from Java. Study the statements below and note the syntactical differences.
12.2.1 Using the Length propertyI mentioned earlier that the Length (with a capital 'L') property of an array in C# gives the total size of an array. For a multi-dimensional array, it gives the total size of the whole array instead of just the size of the ' first-level array'. For example, if you have a 2D rectangular array of 2 rows of 5 cells each created by this statement: int [,] MyArray = new int[2,5]; In Java, MyArray.length will return 2 . In C#, MyArray.Length will return 10 (2 x 5). To obtain the size of the first-level array (the number of rows), use MyArray.GetLength(0) (which returns 2 ). To obtain the size of the second-level array (the number of cells in each row), use MyArray.GetLength(1) (which returns 5 ). Study the output of the following class to confirm your understanding: 1: using System; 2: 3: public class TestClass{ 4: int [,]MyArray = new int[2,5]; // new 2D array 5: 6: public static void Main(){ 7: TestClass c = new TestClass(); 8: Console.WriteLine(c.MyArray .Length ); 9: Console.WriteLine(c.MyArray .GetLength(0) ); 10: Console.WriteLine(c.MyArray .GetLength(1) ); 11: } 12: } Output: c:\expt>test 10 2 5 |