C# Arrays
C# supports single-dimensional arrays, multidimensional arrays (rectangular arrays), and array-of-arrays (jagged arrays).
Single Dimensional Array
When a list of items is identified by one variable name using one subscript, such a variable is called as one dimensional array.
Creation of an array involves 3 steps:
- Declaring array
- Creating memory location
- Putting values into the array
Syntax
DataType[ ] VarName=new DataType[size];
Example
Int[] n=new int[5];
Array Class
Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime.
Some methods of Array Class
| Method | Purpose |
| Array.Sort(VarName ) | Sorts an elements in one dimensional array |
| Array.Reverse( VarName) | Reverse the content of one dimensional array |
| Array.Copy(Source,Dest,length) | Copies one dimensional source array to destination array |
| VarName.GetValue(index) | Gets the value for a given index of the array |
| VarName.SetValue(Value,index) | Sets a value to given index in the array |
Two Dimensional Array
Two dimensional array can be declared as follows:
DataType[,] VarName=new DataType[RowSize,ColSize];
Jagged Arrays
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays."
Example
int[ ][ ] jaggedArray = new int[3][ ];
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];