Array in C# works as it works in any other language except few differences. When we declare an array we must use a square bracket ([ ]) after the data type.
int[ ] number
Unlike c arrays, in c# size of array is not part of its type. This allows user to declare an array without length and later assign an array of same data type of any length to it.
int[] id; // declare numbers as an int array of any size
id = new int[20]; // numbers is a 10-element array
id = new int[50]; // now it's a 20-element array
Declaring Arrays
C# supports three types of array.
- Single Dimensional
- Multi Dimensional
- Array of Array (Jagged Array)
Examples are as follows
Single Dimension: - int[ ] id;
Multi Dimension: - string[ , ] names;
Array-of-arrays: - int [ ] [ ] erNo;
Arrays do not get initialized by just declaring as we did above. Arrays are objects and they must be initialized. Examples are as follows.
Int[ ] id=int[10];
String[ , ] names=[10,10 ];
int[ ] [ ] erNo=[100][100]
We can even mix different kinds of arrays.
int[ ][ , , ][ , ] numbers;
Example
The following is a complete C# program that declares and instantiates arrays as discussed above.
// arrays.cs
using System;
class DeclareArraysSample
{
public static void Main()
{
// Single-dimensional array
int[] id = new int[5];
// Multidimensional array
string[,] names = new string[10,4];
// Array-of-arrays (jagged array)
byte[][] scores = new byte[5][];
// Create the jagged array
for (int i = 0; i < scores.Length; i++)
{
scores[i] = new byte[i+3];
}
// Print length of each row
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine("Length of row {0} is {1}", i, scores[i].Length);
}
}
}
Output
Length of row 0 is 3
Length of row 1 is 4
Length of row 2 is 5
Length of row 3 is 6
Length of row 4 is 7
Initialization of array: - We can initialize an array with any one of the following method
Single-Dimensional Array
int[] id = new int[5] {1, 2, 3, 4, 5};
string[] names = new string[2] {"Abhishek", "Shubham"};
Multidimensional Array
int[,] id = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
string[,] relative = new string[2, 2] { {"Shipra","Prerna"}, {"Aman","Rahul"} };
Jagged Array (Array-of-Arrays)
int[][] id = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
Accessing Array Members
Accessing the array members is as simple as it used to be in c.
Array elements are accesses by index.
int[] id = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
id[4] = 5;
Using foreach on Arrays
int[] id = {4, 5, 6, 1, 2, 3, -2, -1, 0};
foreach (int i in id)
{
System.Console.WriteLine(i);
}
This was a brief description about arrays in c#.
0 Comment(s)