C# Tutorial : Lesson 07 – Creating Value Types & Reference Types – Part II

Partho Sarathi

21 Mar, 2009 · 7 minutes read

  • Share:
foreach statement

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);
}
Param Arrays

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.

Multi Dimensional Arrays

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

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

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}
};
Assigning Values

Values can be assigned as:-

Numbers[1, 2] = 7;
Array Class

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

  • IsFixedSize - Returns a boolean value (True / False) indicating whether the array is of Fixed Size or not.
  • IsReadOnly - Returns a boolean value (True / False) indicating whether the array is Read Only or not.
  • Length - Returns a 32-bit integer that represents the total number of elements across all dimensions in the array.
  • Rank - Returns the number of dimensions (also called the Rank) of the array.
Methods
  • BinarySearch - Performs the faster Binary Search algorithm on the array and returns the number if found.
  • Clear - Resets the value of the supplied range of elements in the array to the default values of the datatype:-
    • int - 0
    • bool - false
    • Reference Data Types - Null
  • Copy - Copies a range of elements to another array along with type casting and boxing as required
  • CopTo - Copies all elements to the specified single dimensional array
  • Find - Searches for the given value and returns its first occurrence in the array
  • FindAll - Returns all occurrences of the searched element in the array
  • GetLength - Returns the 32 bit length of the array
  • GetValue - Returns the value of the specified item in the array
  • IndexOf - Searches for the given value and returns the index of the first position its found in
  • Resize - Resizes the array
  • Reverse - Reverses the order of the elements. (Works only on a single dimensional array)
  • SetValue - Sets the value at the specified location of the array
  • Sort - Sorts the elements. (Works only on a single dimensional array)
Collections

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.

  • Resizing - Arrays cannot be resized natively. So, one has to create a new array and copy the elements of the existing one followed by rearrangement of references for this process. Array List on the other hand work on the concept of Linked List where memory is allocated and deallocated at runtime as and when required.
  • Adding an element - To add an element we need to first create a new array, copy the values before the position where the new element is to be inserted, insert the new element and then insert the remaining elements. Again, a cumbersome process for arrays. Array Lists only need to allocate memory for the new element and resolve the references of the elements on both side of the new element.
  • Deleting an element - All elements after the element to be deleted need to be shifted forward to fill up the vacancy created by the deletion. Array Lists rely on releasing the memory occupied by the element and resolving the references of the elements on both sides.

Common Methods used by the Array List class:-

  • Add - Adds an item at the end of the Array List
  • Clear - Removes all the items from the Array List
  • Insert - Inserts an element into the Array List at the specified position
  • Reverse - Reverses the order of all the elements or a portion of the Array List
  • Remove - Deletes the item at its first occurrence
  • TrimToSize - Sets the maximum capacity to the number of elements currently in the the Array List

Other Classes that the collection namespace provides are:-

  • Queue - A Collection that works on the First-In-First-Out (FIFO) rule. Here, insertion of elements occur at the rear and deletion at the front.
  • Stack - Works on the Last-In-First-Out (LIFO) rule. Both insertion and deletion occur at the top of the stack.
  • Hash Table - It uses unique keys to access/store elements in the collection.
  • Share:

The cleanest blogging platform


2024 © Maxotek. All rights reserved.