07 June 2012

Using Array in C sharp #

In C#(Sharp), Arrays is used to store different items  and perform different operations on them individually. Arrays are declared similar to variables with [] brackets after the data type.  To use the array, it needs to instantiate.


Sample : 
int[] numArr; // declare numbers as an int array of any size
numArr = new int[10];  // numbers is a 10-element array
numArr = new int[20];  // now it's a 20-element array
Array Declaration in C# : Single-dimensional arrays:
int[] numbers = new int[5];  
Multidimensional arrays:
string[,] names = new string[5,4]; 
Array Initialization:
int[] myArray;

myArray = new int[] {1, 3, 5, 7, 9};   // OK  
Passing Arrays as Parameters
myMethod( myArray);
static void myMethod(string[] w){
for (int i = 0 ; i < w.Length ; i++)
Console.Write(w[i] + "{0}", i < w.Length - 1 ? " " : "");
Console.WriteLine();
}  
Special Note: In C#, during the declaring of an array, square brackets [] must come after the type, not the identifier. Writing brackets after identifier is not legal syntax in C#. Example:
int[] table; // not int table[];  

(If you found this article useful then share with your friends.)

No comments: