Array is a useful data type used for storing multiple values.Arrays in c# like other languages are used for storing multiple variables of the same type.So instead of using multiple variables for storing values
we can use arrays.
Array declaration
We can declare and create array in a single line as:
int[] nos=new int[10];
or we can declare and then create array separately:
int[] nos; nos=new int[10];
Since arrays are implemented as objects in c# ,so array object is actually created only when we instantiate an array using new operator.
To initialize array we can assign the values when declaring array.We don’t need to assign array size when declaring and assigning array in the same line.
int[] nos = { 1, 2, 3, 4, 5, 6 };
We can iterate array elements using for loop as in other languages:
for (int i = 0; i < nos.Length;i++ ) { Console.WriteLine(nos[i]); }
Since array index starts from 0 and continues till size of array minus 1 ,we start from 0 index when using for loop.
But a better way to iterate array elements is to use foreach loop:
foreach(int no in nos) { Console.WriteLine(no); }
An important feature of arrays in c# is that array implements IEnumerable interface so we can use the methods of IEnumerable interface such as foreach loop.
Every array in C# is an object derived from the System.Array class.So the members of System.Array class can be used by every array.
Following are some of the useful methods defined by the array class
- Sort sorts the array elements
- ToString returns string
- Resize<T> modifies the size of the array
- Reverse reverses the elements of the array
- GetLength returns length of the array
- Find<T> used to search for an element in array as defined by the predicate passed as argument
- Exists<T> used to search for existence of an element in array as defined by the predicate passed as argument
Leave a Reply