CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
int[][] myJagArray = new int[5][];
// Create the jagged array.
for (int i = 0; i < myJagArray.Length; i++)
myJagArray[i] = new int[i + 7];
}
// Print each row (remember, each element is defaulted to zero!).
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < myJagArray[i].Length; j++)
Console.Write(myJagArray[i][j] + " ");
Console.WriteLine();
}
Console.WriteLine();
Figure 4-2 shows the output of calling each of the RectMultidimensionalArray() and
JaggedMultidimensionalArray() methods within Main().
Figure 4-2. Rectangular and jagged multidimensional arrays
Arrays As Arguments or Return Values
After you have created an array, you are free to pass it as an argument or receive it as a member return
value. For example, the following PrintArray() method takes an incoming array of ints and prints each
member to the console, while the GetStringArray() method populates an array of strings and returns it
to the caller:
static void PrintArray(int[] myInts)
{
for(int i = 0; i < myInts.Length; i++)
Console.WriteLine("Item {0} is {1}", i, myInts[i]);
}
static string[] GetStringArray()
{
string[] theStrings = {"Hello", "from", "GetStringArray"};
return theStrings;
}
137