21 Mar, 2009 · 7 minutes read
This statement is explicitly used to traverse through arrays. The benefit of using foreachover the normal forstatement is that it is not necessary to check the size of the array while using the former.
Syntax:-
foreach(type identifier in expression)
{
statement 1;
statement 2;
…
}
Suppose we have an array StudentNamescontaining the name of all the students in a class. We need to display the name of each one of them on screen. First we will see how it can be done using the forloop.
string[] StudentNames = new string[] {"Peter", "Tony", "Bruce", "Scott", "Clark", "Kenshin"};
for (int I = 0; I < StudentNames.Length; I )
{
Console.WriteLine(StudentNames[I]);
}
Now we'll use the foreachstatement to do this.
string[] StudentNames = new string[] {"Peter", "Tony", "Bruce", "Scott", "Clark", "Kenshin"};
foreach (string StudentName in StudentNames)
{
Console.WriteLine(StudentName);
}
Remember the Console.WriteLinemethod which outputs the result using a string format followed by the additional values as input parameters. For example: Console.WriteLine("The sum of {0} and {1} is {2}", Num1, Num2, Num1 Num2);would display The sum of 5 and 6 is 11for values 5 and 6 for Num1 and Num2 respectively. What is worth noting here, is that WriteLine()can take any number of parameters after the string format. So, something like this would work as well:-
Console.WriteLine("The Prime Numbers -> {0}, {1}, {2}, {3}, {4}", 2, 3, 5, 7, 11);
This is done by the paramarray data type. Example:-
public static int Sum(params int[] Numbers)
{
int Sum = 0;
foreach (int Number in Numbers)
{
Sum = Number;
}
return Sum;
}
This is a function to return the sum of any number of numbers. The numbers to be summed are passed as parameters during the function call as: Sum(4, 69, 13, 99);
Note: param array should be the last parameter in the function signature which also means that only one param array can be used in a function. Why is this done? Consider the following function signature: public static int MyFunction(params int[] A, int C). How would we call the function if this were to be allowed? MyFunction(1, 2, 3, 4, 5);How can the compiler determine where the values for the param array A finish? Actually, if a reverse scanning of parameters were to be done, this could be determined. But that would increase useless complexity of having to implement this along with the normal forward scanning of parameters.
Up until now, we have only worked with Single Dimensional arrays. Now we shall see how the Multi Dimensional arrays are declared, initialized and manipulated. The pictures below show how the Single and Double Dimensional arrays are represented.
Single Dimensional Array
Multi Dimensional Array
While, the Single Dimensional arrays are represented as a single row of elements, Double Dimensional arrays are represented by multiple rows. Similarly, arrays with 3 dimensions would be represented in 3D space along the three axes.
Declaration is done by the syntax:-
datatype [ , ] VariableName;
The number of commas ( , ) inside the square brackets [ ] should be one less than the number of dimensions required for the array.
Example Usage:-
int [ , ] Numbers;
Initialization is done in a way where each row is treated like a single dimensional array. Example:-
int[,] Numbers = new int[3, 3]
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Values can be assigned as:-
Numbers[1, 2] = 7;
The Arrayclass defined in the Systemnamespace serves as the base class for all the arrays in the Common Language Runtime. It can be used to create, manipulate, search and sort arrays.
Some of the common Properties and methods are summarized below.
Properties
An integer array can only store integers. Same goes for any other array type - string, boolean, etc. Collectionsovercome this limitation of arrays and can store elements of different types as items. This is possible because Collections actually store references and not values. We use the System.Collectionsnamespace to work with collections.
Boxing- No, not the Sport! Boxing is the automatic conversion of value types to reference types allowing them to be stored in collections.
Unboxing- The reverse of the former, conversion of reference type to value type.
Because Collections store references, it is necessary to do the above conversions while storing and retrieving values in Collections.
Array List- Array List is a better alternative to arrays because of the following advantages it offers over arrays. It resides in the System.Collection namespace.
Common Methods used by the Array List class:-
Other Classes that the collection namespace provides are:-