Arrays in General
C# arrays are zero indexed; that is, the array indexes start at zero. Arrays in C# work similarly to how arrays work in most other popular languages There are, however, a few differences that you should be aware of.When declaring an array, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.
int[] table; // not int table[];
int[] numbers; // declare numbers as an int array of any size numbers = new int[10]; // numbers is a 10-element array numbers = new int[20]; // now it's a 20-element array
Declaring Arrays
C# supports single-dimensional arrays, multidimensional arrays (rectangular arrays), and array-of-arrays (jagged arrays). The following examples show how to declare different kinds of arrays:Single-dimensional arrays:
int[] numbers;
string[,] names;
byte[][] scores;
Single-dimensional arrays:
int[] numbers = new int[5];
string[,] names = new string[5,4];
byte[][] scores = new byte[5][]; for (int x = 0; x < scores.Length; x++) { scores[x] = new byte[4]; }
int[,,] buttons = new int[4,5,3];
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[] numbers = new int[5]; // Multidimensional array string[,] names = new string[5,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
Initializing Arrays
C# provides simple and straightforward ways to initialize arrays at declaration time by enclosing the initial values in curly braces ({}). The following examples show different ways to initialize different kinds of arrays.Note If you do not initialize an array at the time of declaration, the array members are automatically initialized to the default initial value for the array type. Also, if you declare the array as a field of a type, it will be set to the default value null when you instantiate the type.
Single-Dimensional Array
int[] numbers = new int[5] {1, 2, 3, 4, 5}; string[] names = new string[3] {"Matt", "Joanne", "Robert"};
int[] numbers = new int[] {1, 2, 3, 4, 5}; string[] names = new string[] {"Matt", "Joanne", "Robert"};
int[] numbers = {1, 2, 3, 4, 5}; string[] names = {"Matt", "Joanne", "Robert"};
Multidimensional Array
int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} };
int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Albert"} };
int[,] numbers = { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = { {"Mike", "Amy"}, {"Mary", "Albert"} };
Jagged Array (Array-of-Arrays)
You can initialize jagged arrays like this example:int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
Accessing Array Members
Accessing array members is straightforward and similar to how you access array members in C/C++. For example, the following code creates an array callednumbers
and then assigns a 5
to the
fifth element of the array:int[] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; numbers[4] = 5;
5
to the member located at [1, 1]
:int[,] numbers = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} }; numbers[1, 1] = 5;
int[][] numbers = new int[][] { new int[] {1, 2}, new int[] {3, 4, 5} };
numbers[0][0] = 58; numbers[1][1] = 667;
Arrays are Objects
In C#, arrays are actually objects. System.Array is the abstract base type of all array types. You can use the properties, and other class members, that System.Array has. An example of this would be using the Length property to get the length of an array. The following code assigns the length of thenumbers
array, which is 5
, to a variable called LengthOfNumbers
:int[] numbers = {1, 2, 3, 4, 5}; int LengthOfNumbers = numbers.Length;
Using foreach on Arrays
C# also provides the foreach statement. This statement provides a simple, clean way to iterate through the elements of an array. For example, the following code creates an array callednumbers
and
iterates through it with the foreach statement:int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0}; foreach (int i in numbers) { System.Console.WriteLine(i); }
int[,] numbers = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}}; foreach(int i in numbers) { Console.Write("{0} ", i); }
9 99 3 33 5 55
An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Declaring Arrays
To declare an array in C#, you can use the following syntax:datatype[] arrayName;where,
- datatype is used to specify the type of elements to be stored in the array.
- [ ] specifies the rank of the array. The rank specifies the size of the array.
- arrayName specifies the name of the array.
double[] balance;
Initializing an Array
Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array.Array is a reference type, so you need to use the new keyword to create an instance of the array.
For example,
double[] balance = new double[10];
Assigning Values to an Array
You can assign values to individual array elements, by using the index number, like:double[] balance = new double[10]; balance[0] = 4500.0;You can assign values to the array at the time of declaration, like:
double[] balance = { 2340.0, 4523.69, 3421.0};You can also create and initialize an array, like:
int [] marks = new int[5] { 99, 98, 92, 97, 95};In the preceding case, you may also omit the size of the array, like:
int [] marks = new int[] { 99, 98, 92, 97, 95};You can also copy an array variable into another target array variable. In that case, both the target and source would point to the same memory location:
int [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks;When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example for an int array all elements would be initialized to 0.
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example:double salary = balance[9];Following is an example which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays:
using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; } /* output each array element's value */ for (j = 0; j < 10; j++ ) { Console.WriteLine("Element[{0}] = {1}", j, n[j]); } Console.ReadKey(); } } }When the above code is compiled and executed, it produces following result:
Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109
Using the foreach Loop
In the previous example, we have used a for loop for accessing each array element. You can also use a foreach statement to iterate through an array.using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n is an array of 10 integers */ /* initialize elements of array n */ for ( int i = 0; i < 10; i++ ) { n[i] = i + 100; } /* output each array element's value */ foreach (int j in n ) { int i = j-100; Console.WriteLine("Element[{0}] = {1}", i, j); i++; } Console.ReadKey(); } } }When the above code is compiled and executed, it produces following result:
Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109
C# Arrays in Detail
Arrays are important to C# and should need lots of more detail. There are following few important concepts related to array which should be clear to a C# programmer:Concept | Description |
---|---|
Multi-dimensional arrays | C# supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. |
Jagged arrays | C# supports multidimensional arrays, which are arrays of arrays. |
Passing arrays to functions | You can pass to the function a pointer to an array by specifying the array's name without an index. |
Param arrays | This is used for passing unknown number of parameters to a function. |
The Array Class | Defined in System namespace, it is the base class to all arrays, and provides various properties and methods for working with arrays |
No comments:
Post a Comment