Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0052 Arrays as Arguments

Passing Single-Dimensional Arrays As Arguments For example, the following statement sends an array to a print method. class MainClass { public static void Main() { int[] theArray = { 1, 3, 5, 7, 9 }; PrintArray(theArray); } public static void PrintArray(int[] arr) { foreach (int i in arr) { System.Console.WriteLine(i); } } } The output: 1 3 5 7 9 You can initialize and pass a new array in one step, as is shown in the following example. class MainClass { public static void Main() { PrintArray(new int[] { 1, 3, 5, 7, 9 }); } static void PrintArray(int[] arr) { foreach(int i in arr){ System.Console.WriteLine(i); } } } The output: 1 3 5 7 9 In the following example, an array of strings is initialized and passed as an argument. class MainClass { static void PrintArray(string[] arr) { for (int i = 0; i < arr.Length; i++) { System.Console.Write(arr[i] + "{0}", i < arr.Length - 1 ? " " : ""); } } static void Main() { // Declare and initialize an array. string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // Pass the array as an argument to PrintArray. PrintArray(weekDays); } } The output: Sun Mon Tue Wed Thu Fri Sat