Friday, January 11, 2013

Arrays As Parameters (and Return Values) in C#.NET


Once you have created an array, you are free to pass it as a parameter and receive it as a member return value. For example, the following PrintArray() method takes an incoming array of strings and prints each member to the console, while the GetStringArray() method populates an array 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; 

These methods may be invoked from a Main() method as so: 

static void Main(string[] args) 
int[] ages = {20, 22, 23, 0} ; 
PrintArray(ages); 
string[] strs = GetStringArray(); 
foreach(string s in strs) 
Console.WriteLine(s); 
Console.ReadLine(); 
}

No comments:
Write comments
Recommended Posts × +