Breaking News
yeni film izle hd film seyret film izle

Arrays in C#

An array is a set of uniform data elements, represented by a single variable name. The individual elements are accessed using the variable name and one or more indexes between square brackets, as given below:
 
MyArray[4]
 
In the above line, MyArray is the array name and [4] is the array index. Let’s start with some important definitions having to do with arrays in C#.
 
Elements: The individual data items of an array are called elements. All elements of an array must be of the same type.

Rank/dimensions: Arrays can have any positive number of dimensions. The number of dimensions an array has is called its rank.

Dimension length: Each dimension of an array has a length, which is the number of positions in that direction.

Array length: The total number of elements contained in an array, in all dimensions, is called the length of the array.

 
By default in C#, an array index always starts with zero. That means first item of an array will be stored at 0th position. The position of the last item on an array will total number of items-
 
1. In C#, arrays can be declared as fixed length or dynamic. Fixed length array can stores a predefined number of items, while size of dynamic arrays increases as you add new items to the array. You can declare an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined.
 
For example, the following like declares a dynamic array of integers.
 
int [] intArray;
 
The following code declares an array, which can store 5 items starting from index 0 to 4.
 
int [] intArray;
intArray = new int[5];
 
The following code declares an array that can store 100 items starting from index 0 to 99.
 
int [] intArray;
intArray = new int[100];
 
Types of Arrays
 
There are two types of array in C#:
 
• One-Dimensional Arrays: One-dimensional arrays can be thought of as a single line, or vector, of elements.
 
• Multidimensional Arrays: Multidimensional arrays are combination of single dimension array such that each position in the primary vector is itself an array, called a sub-array. Positions in the sub-array vectors can themselves be sub-arrays.
 
There are two types of multidimensional arrays-
 
? Rectangular arrays
? Jagged arrays
 
Which have the following characteristics –
 
• Rectangular Arrays
 
o Rectangular arrays are multidimensional arrays where all the sub-arrays in a particular dimension have the same length

o Rectangular arrays are always use a single set of square brackets, regardless of the number of dimensions

 
• Jagged Arrays
 
o Jagged arrays are multidimensional arrays where each sub-array is an independent array

o Jagged array can have sub-arrays of different lengths

o Jagged array use a separate set of square brackets for each dimension of the array

 
jagArray1[2][7][4] // Three sets of square brackets
 
The given picture shows the kinds of arrays available in C#.
 
Image:7230f1402.jpg
One-dimensional, rectangular, and jagged arrays
 
An Array as an Object
 
An array instance is an object whose type derives from class System.Array. Since arrays are derived from this BCL base class, they inherit a number of useful members from it, such as
 
• Rank: A property that returns the number of dimensions of the array

• Length: A property that returns the length of the array (the total number of elements in the array)

 
Arrays are reference types, and as with all reference types, have both a reference to the data and the data object itself. The reference is in either the stack or the heap, and the data object itself will always be in the heap. The given picture shows the memory configuration and components of an array.
 
Image:7230f1403.jpg
Structure of an array
 
Although an array is always a reference type, the elements of the array can be either value types or reference types.
 
• An array is called a value type array if the elements stored are value types.
 
• An array is called a reference type array if the elements stored in the array are references of reference type objects.
 
The given picture shows a value type array and a reference type array.
 
Image:7230f1404.jpg
Elements can be values or references
 
Single Dimension Arrays
 
Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store number of items of a predefined type. All items in a single dimension array are stored in a row starting from 0 to the size of array – 1.
 
In C# language, arrays are objects. That means declaring an array doesn’t create an array. After declaring an array, you need to instantiate an array by using the “new” operator.
 
int [] intArray;
intArray = new int[3];
 
Array declarations in C# are pretty simple. You put array items in curly braces ({}). If an array is not initialized, its items are automatically initialized to the default initial value for the array type if the array is not initialized at the time it is declared. The following code declares and initializes an array of three items of integer type.
 
int [] intArray;
intArray = new int[3] {0, 1, 2};
 
The given code declares and initializes an array of 5 string items.
 
string[] strArray = new string[5] {“Ronnie”, “Jack”, “Lori”, “Max”, “Tricky”};
 
You can even direct assign these values without using the new operator.
 
string[] strArray = {“Ronnie”, “Jack”, “Lori”, “Max”, “Tricky”};
 
Multi Dimension Arrays or Rectangular Array
 
A multidimensional array is an array with more than one dimension. A multi dimension array is declared as following:
 
string[,] strArray;
 
After declaring an array, you can specify the size of array dimensions if you want a fixed size array or dynamic arrays. For example, the following code two examples create two multi dimension arrays with a matrix of 3×2 and 2×2. The first array can store 6 items and second array can store 4 items respectively.
 
int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
string[,] names = new string[2, 2] { {“Rosy”,”Amy”}, {“Peter”,”Albert”} };
 
If you don’t want to specify the size of arrays, just don’t define a number when you call new operator. For example,
 
int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };
string[,] names = new string[,] { {“Rosy”,”Amy”}, {“Peter”,”Albert”} };
 
You can also omit the new operator as we did in single dimension arrays. You can assign these values directly without using the new operator. For example:
 
int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = { {“Rosy”, “Amy”}, {“Peter”, “Albert”} };
 
One-Dimensional Array or a Rectangular Array
 
Syntactically, one-dimensional arrays and rectangular arrays are very similar, so here, both will be treated together. Jagged arrays will be treated separately. To declare a one-dimensional or rectangular array, use a single set of square brackets between the type and the variable name.
 
The rank specifiers are commas between the brackets. They specify the number of dimensions the array will have. The rank is the number of commas, plus one. For example, no commas indicates a one-dimensional array, one comma indicates a two-dimensional array, and so forth.
 
The base type, together with the rank specifiers, is the type of the array. For example, the following line of code declares a one-dimensional array of longs. The type of the array is long [], which is read as “an array of longs”.
 
long[ ] secondArray;
 	where: 
 	the rank specifiers = 1 (i.e. the blank in "[ ]") 
 	the array type is long 
 
The following code shows examples of declarations of rectangular arrays.

Notice that

 
• You can have as many rank specifiers as you need.
 
• You cannot place array dimension lengths in the array type section. The rank is part of the array’s type, but the lengths of the dimensions are not part of the type.
 
• When an array is declared, the number of dimensions is fixed. The length of the dimensions, however, is not determined until the array is instantiated.
 
int[,,]   firstArray;   // Array type: 3-D array of int
 	int[,]    arr1;         // Array type: 2-D array of int
 	long[,,]  arr3;         // Array type: 3-D array of long 
 	where: 
 	Rank specifiers = ",," and "," and ",," 

 	long[3,2,6] SecondArray; // Wrong!  Compile error 
 
Dimension lengths (i.e. “3,2,6”) not allowed!
 
Note Unlike C/C++, the brackets follow the base type, not the variable name.
 
Instantiating a One-Dimensional or a Rectangular Array
 
To instantiate an array, you use an array creation expression. An array creation expression consists of the new operator, followed by the base type and followed by a pair of square brackets. The length of each dimension is placed in a comma-separated list between the brackets.
 
The following are examples of one-dimensional array declarations:
 
• Array arr2 is a one-dimensional array of four ints.

• Array mcArr is a one-dimensional array of four MyClass references.

• Their layouts in memory are shown in picture below.

 
int[] arr2 = new int[4];
 		MyClass[] mcArr = new MyClass[4];
 		where: 
 		no. elements = 4 (i.e. "[4]") 
 		Array creation expression = "new MyClass[4]" 
 
The following is an example of a rectangular array. Array arr3 is a three-dimensional array.
 
• The length of the array is 3 * 6 * 2 = 36.
• Its layout in memory is shown in given picture below.
 
int[,,] arr3 = new int[3,6,2] ;
where: 
Lengths of the dimensions = "3,6,2" 
 
At the time of instantiation, each element is automatically initialized to the default initialization value for the type of the element.
 
Image:7230f1405.jpg
 
Declaring and instantiating arrays
 
Note Array creation expressions do not contain parentheses—even for reference type arrays.
 
Accessing Array Elements
 
An array element is accessed using an integer value as an index into the array.
 
• Each dimension uses 0-based indexing.
• The index is placed between square brackets following the array name.
 
The following code shows examples of declaring, writing to, and reading from a one- dimensional and a two-dimensional array:
 
int[]intArr1 = new int[15];  // 1-D example
   	intArr1[2] = 10;             // Write to element 2 of the array.
   	int var1 = intArr1[2];       // Read from element 2 of the array.
 
   
  int[,] intArr2 = new int[5,10];  // 2-D example
   	intArr2[2,3]   = 7;              // Write to the array.
   	int var2 = intArr2[2,3];   	  // Read from the array. 
 
The following code shows the full process of creating and accessing a one-dimensional array:
 
int[] myIntArray;          // Declare the array.
 
   	myIntArray = new int[4];   // Instantiate the array.
 
   	for( int i=0; i<4; i++ )   // Set the values.
      		myIntArray[i] = i*10;
 
   // Read and display the values of each element.
   for( int i=0; i<4; i++ )  
      Console.WriteLine("Value of element {0} = {1}", i, myIntArray[i]);
This code produces the following output: 
Value of element 0 is 0
Value of element 1 is 10
Value of element 2 is 20
Value of element 3 is 30 
 
Initializing an Array
 
Array elements are always initialized. If they are not explicitly initialized, the system will automatically initialize them to default values.
 
Automatic Initialization of an Array
 
When any type of array is created, each of the elements is automatically initialized to the default value for the type. The default values for the predefined types are 0 for integer types, 0.0 for floating point types, false for Booleans, and null for reference types.
 
For example, the following code creates an array and initializes its four elements to the default value 0. The given picture illustrates the layout in memory.
 
int[] intArr = new int[4];
 
img
Automatic initialization of a one-dimensional array
 
Explicit Initialization of a One-Dimensional Array
 
For a one-dimensional array, you can set explicit initial values by including an initialization list instantly after the array creation expression of an array instantiation.
 
• The initialization values must be separated by commas and enclosed in a set of curly braces.

• Notice, however, that nothing separates the array creation expression and the initialization list. That is, there is no equals sign or other connecting operator.

 
For example, the following code creates an array and initializes its four elements to the values between the curly braces. The given picture illustrates the layout in memory.
 
int[] intArr = new int[4] { 10, 20, 30, 40 };
where: 
Initialization list = "10, 20, 30, 40" 
No connecting operator (i.e. the space in "[4] {") 
 
Image:7230f1407.jpg
 
Explicit initialization of a one-dimensional array
 
Explicit Initialization of a Rectangular Array
 
To explicitly initialize a rectangular array:
 
• Each vector of initial values must be enclosed in curly braces.

• Each dimension must also be nested and enclosed in curly braces.

• In addition to the initial values, the initialization lists and components of each dimension must also be separated by commas.

 
For example, the following code shows the declaration of a two-dimensional array with an initialization list. The given picture illustrates the layout in memory.
 
int[,] intArray2 = new int[3,2]
   { {10, 1}, {2, 10}, {11, 9} } ;
where: 
Initialization lists separated by commas 

(i.e. the commas outside the brackets "{10, 1}, {2, 10}, {11, 9}") 
 
Image:7230f1408.jpg
Initializing a rectangular array
 
Syntax Tips for Initializing a Rectangular Array
 
Rectangular arrays are initialized with nested, comma-separated initialization lists. The initialization lists are nested in curly braces. This can sometimes be confusing, so to get the nesting, grouping, and commas right, the following tips can be useful:
 
• Commas are used as separators between all elements and groups.

• Commas are not placed between left curly braces.

• Commas are not placed before a right curly brace.

• Read the rank specifications from left to right, designating the last number as “elements” and all the others as “groups.”

 
For example, read the following declaration as “intArray has four groups of three groups of two elements”.
 
int[,,] intArray = new int[4,3,2]
   {
    	{ {8, 6},  {5,  2}, {12, 9} },
    	{ {6, 4},  {13, 9}, {18, 4} },
    	{ {7, 2},  {1, 13}, {9,  3} },
    	{ {4, 6},  {3,  2}, {23, 8} }
   };
where: 
Initialization lists, nested and separated by commas 
 
Shortcut Syntax for declaration, creation and initialization
 
When we want to brushing array declaration, array creation, and array initialization in a single statement, then the array creation expression part of the syntax can be left out. This shortcut syntax is given below:
 
int [] arr1 = new int[3] (10, 20, 30);
int [] arr1 =		 (10, 20, 30);
Both the above codes are equivalent.

int [,] arr = new int[2,3]  ({0,1,2},{10,11,12});
int [,] arr =		  ({0,1,2},{10,11,12});
Both the above codes are equivalent.
Shortcut for array declaration, creation, and initialization
 
Example:
 
Now that you have all the pieces, they can be put together in a full example. The following code creates, initializes, and uses a rectangular array.
 
// Declare, create, and initialize the array.
int[,] arr = new int[2,3] {{0, 1, 2}, {10, 11, 12}};
 
// Print the values.
for( int i=0; i<2; i++ )
   for( int j=0; j<3; j++ )
      Console.WriteLine
         ("Element [{0}, {1}] is {2}", i, j, arr[i,j]);
 
This code produces the following output:
 
Element [0, 0] is 0
Element [0, 1] is 1
Element [0, 2] is 2
Element [1, 0] is 10
Element [1, 1] is 11
Element [1, 2] is 12 
 
Jagged Arrays
 
A jagged array is an array of arrays. Unlike rectangular arrays, the sub-arrays of a jagged array can have different numbers of elements.
 
For example, the following code declares a two-dimensional jagged array. The array’s layout in memory is shown in the given picture.
 
• The length of the first dimension is 3.

• The declaration can be read as “jagArray is an array of three arrays of ints.”

• Notice that the figure shows four array objects—one for the top-level array, and three for the sub-arrays.

 
// Declare and create top-level array.
int[][] jagArr = new int[3][];
 
// Declare and create sub-arrays. 
...
 
Image:7230f1410.jpg
A jagged array is an array of arrays.
 
Declaring a Jagged Array
 
The declaration syntax for jagged arrays requires a separate set of square brackets for each dimension. The number of sets of square brackets in the declaration of the array variable determines the rank of the array.
 
• A jagged array can be of any number of dimensions greater than one.

• As with rectangular arrays, dimension lengths cannot be included in the array type section of the declaration.

 
int[][]   SomeArr;   // Rank = 2
int[][][] OtherArr;  // Rank = 3 
where: 
Rank specifiers = "[][]" and "[][][]" 
Array types = "int[][]" and "int[][][]" 
Array names = "SomeArr" and "OtherArr" 
 
Shortcut Instantiation
 
You can combine the jagged array declaration with the creation of the first-level array using an array creation expression, such as in the following declaration. The result is shown in the given picture.
 
int[][] jagArr = new int[3][];
where: 
Three sub-arrays (i.e. "[3]") 

 
Image:7230f1411.jpg
Figure 14-11. Shortcut first-level instantiation
 
You cannot instantiate more than the first-level array in the declaration statement.
 
int[][] jagArr = new int[3][4];   // Wrong! Compile error 
where: 
Allowed: "[3]" 
Not allowed: "[4]" 
 
Instantiating a Jagged Array
 
Unlike other types of arrays, you cannot fully instantiate a jagged array in a single step. Since a jagged array is an array of independent arrays—each array must be created separately. Instantiating a full jagged array requires the following steps:
 
1. First, instantiate the top-level array.

2. Next, instantiate each sub-array separately, assigning the reference to the newly created array to the appropriate element of its containing array.

 
For example, the following code piece shows the declaration, instantiation, and initialization of a two-dimensional jagged array. Notice in the code that the reference to each sub-array is assigned to an element in the top-level array. The progression of steps 1 through 4 in the code corresponds to the numbered representations in the given picture.
 
// 1. Instantiate top level
int[][] Arr = new int[3][];                  
 
// 2. Instantiate sub-arrays
Arr[0] = new int[] {10, 20, 30};             
Arr[1] = new int[] {40, 50, 60, 70};         
Arr[2] = new int[] {80, 90, 100, 110, 120};
 
Image:7230f1412.jpg
Creating a two-dimensional jagged array
 
Sub-Arrays in Jagged Arrays
 
Since the sub-arrays in a jagged array are themselves arrays, it is possible to have rectangular arrays inside jagged arrays. For example, the following code creates a jagged array of three two- dimensional rectangular arrays and initializes them with values. It then displays the values.
 
• The structure is illustrated in the given picture.

• The code also uses the GetLength(int n) method of arrays, inherited from System.Array, to get the length of the specified dimension of the array.

 
// An array of 2-D arrays
int[][,] Arr; 
 
// Instantiate an array of three 2-D arrays.        
Arr = new int[3][,];  
 
Arr[0] = new int[,] 
   { { 10, 20 }, { 100, 200 } };
Arr[1] = new int[,] 
   { { 30, 40, 50 }, { 300, 400, 500 } };
Arr[2] = new int[,] 
   { { 60, 70, 80, 90 }, { 600, 700, 800, 900 } };
 
       //Get length of dimension 0 of Arr
for (int i = 0; i < Arr.GetLength(0); i++)
{         //Get length of dimension 0 of Arr[ i ] 
   for (int j = 0; j < Arr[i].GetLength(0); j++)
   {         //Get length of dimension 1 of Arr[ i ] 
      for (int k = 0; k < Arr[i].GetLength(1); k++) {
          Console.WriteLine
                     ("[{0}][{1},{2}] = {3}", i, j, k, Arr[i][j, k]);
      }
      Console.WriteLine("");
   }
   Console.WriteLine("");
}
 
Image:7230f1413.jpg
Jagged array of three two-dimensional arrays
 
Comparing Rectangular and Jagged Arrays
 
The structure of rectangular and jagged arrays is significantly different. e.g., the given picture shows the structure of a rectangular three-by-three array, and a jagged array of three one-dimensional arrays of length 3.
 
• Both arrays hold nine integers, but as you can see, their structures are quite different.

• The rectangular array has a single array object, while the jagged array has four array objects.

 
Image:7230f1414.jpg
Comparing the structure of rectangular and jagged arrays
 
One-dimensional arrays have specific instructions in the CIL that allow them to be optimized for performance. Rectangular arrays do not have these instructions, and are not optimized to the same level. Because of this, it can sometimes be more efficient to use jagged arrays of one-dimensional arrays—which can be optimized—than rectangular arrays, which cannot.
 
On the other hand, the programming complexity can be less for a rectangular array because it can be treated as a single unit, rather than an array of arrays.
 
Using foreach Statement with Single Dimensional Arrays
 
The foreach statement allows you to sequentially access each element in an array. It is actually a more general construct in that it also works with other collection types—but here, we will only discuss its use with arrays.
 
The important points of the foreach statement are the following:
 
• The iteration variable is a temporary, read-only variable of the same type as the elements of the array. The foreach statement uses the iteration variable to sequentially represent each element in the array.

• The syntax of the foreach statement is where

• Type is the type of the elements of the array.

• Identifier is the name of the iteration variable.

• ArrayName is the name of the array to be processed.

• Statement is a simple statement or a block that is executed once for each element in the array.

 
foreach( Type Identifier in ArrayName )
where: 
Iteration variable declaration = "Type Identifier" 
Statement is the entire line 
 
The way the foreach statement works is the following:
 
• It starts with the first element of the array and assigns that value to the iteration variable.

• It then executes the body of the statement. Inside the body, you can use the iteration variable as a read-only alias for the array element.

• After the body is executed, the foreach statement selects the next element in the array and repeats the process.

 
In this way, it cycles through the array, allowing you to access each element one by one. For example, the following code shows the use of a foreach statement with a one-dimensional array of four integers:
 
• The WriteLine statement, which is the body of the foreach statement, is executed once for each of the elements of the array.

• The first time through the loop, iteration variable item has the value of the first element of the array. Each successive time, it will have the value of the next element in the array.

 
int[] arr1 = {10, 11, 12, 13};
 
foreach( int item in arr1 )
   Console.WriteLine("Item Value: {0}", item);
where: 
Iteration variable declaration = "int item" 
Iteration variable use = "item);" 
 
Array Iteration with Read-Only Variable
 
Since the value of the iteration variable is read-only, clearly, it cannot be changed. But this has different effects on value type arrays and reference type arrays.
 
For value type arrays, this means that you cannot change the data of the array. e.g., in the following code, the attempt to change the data in the iteration variable produces a compile-time error message:
 
int[] arr1 = {10, 11, 12, 13};	
 
   foreach( int item in arr1 )
      item++;   // Wrong... 
      //Changing variable value is not allowed 
 
For reference type arrays, you still cannot change the iteration variable, but the iteration variable only holds the reference to the data, not the data itself. You can, therefore, change the data through the iteration variable.
 
The following code creates an array of four MyClass objects and initializes them. In the first foreach statement, the data in each of the objects is changed. In the second foreach statement, the changed data is read from the objects.
 
   class MyClass
   {
      public int MyField = 0;
   }
 
   class Program 
   {
      static void Main() 
      {
         MyClass[] mcArray = new MyClass[4];            // Create array
         for (int i = 0; i < 4; i++)
         {
            mcArray[i] = new MyClass();                 // Create class objects
            mcArray[i].MyField = i;                     // Set field
         }
         foreach (MyClass item in mcArray)
            item.MyField += 10;                         // Change the data.
 
         foreach (MyClass item in mcArray)
            Console.WriteLine("{0}", item.MyField);     // Read the changed data.
      }
   }
 
This code produces the following output:
 
10
11
12
13
 
Using foreach Statement with Multidimensional Arrays
 
In a multidimensional array, the elements are processed in the order in which the rightmost index is incremented fastest. When the index has gone from 0 to length – 1, the next index to the left is incremented, and the indexes to the right are reset to 0.
 
Example with a Rectangular Array
 
The following example shows the foreach statement used with a rectangular array:
 
class Sample
   {
      static void Main()
      {
         int nTotal = 0;
         int[,] arr1 = { {10, 11}, {12, 13} };
 
         foreach( int element in arr1 )
         {
            nTotal += element;
            Console.WriteLine
               ("Element: {0}, Current Total: {1}", 
                  element, nTotal);
         }
      }
   }
 
The output is the following:
 
Element: 10, Current Total: 10
Element: 11, Current Total: 21
Element: 12, Current Total: 33
Element: 13, Current Total: 46 
 
Example with a Jagged Array
 
Since jagged arrays are arrays of arrays, separate foreach statements must be used for each dimension in the jagged array. The foreach statements must be nested properly to make sure that each nested array is processed properly.
 
For example, in the following code, the first foreach statement cycles through the top-level array—arr1—selecting the next sub-array to process. The inner foreach statement processes the elements of that sub-array.
 
static void Main()
   {
      int nTotal = 0;
      int[][] arr1 = new int[2][];
      arr1[0] = new int[] { 10, 11 };
      arr1[1] = new int[] { 12, 13, 14 };
 
      // Process the top level.
      foreach (int[] array in arr1)       
      {
         Console.WriteLine("Starting new array\n");
         // Process the second level.
         foreach (int item in array)      
         {
            nTotal += item;
            Console.WriteLine
               (" Item: {0}, Current Total: {1}", 
                  item, nTotal);
         }
      }
   }
 
The output is the following:
 
Starting new array Item: 10, Current Total: 10
Item: 11, Current Total: 21
Starting new array
Item: 12, Current Total: 33
Item: 13, Current Total: 46
Item: 14, Current Total: 60 
 
Array Covariance
 
Under certain conditions, you can assign an object to an array element even if the object is not of the array’s base type. This property is called covariance.
 
You can use covariance if
 
• The array is a reference type array.

• There is an implicit or explicit conversion between the type of the object you are assigning and the array’s base type.

 
Since there is always an implicit conversion between a derived class and its base class, you can always assign an object of a derived class to an array declared for the base class.
 
For example, the following code declares two classes, A and B, where class B derives from class A. The last line shows covariance by assigning objects of type B to array elements of type A. The memory layout for the code is shown in the given picture.
 
class A { ... }      // Base class
   class B : A { ... }  // Derived class
 
   class Program {
      static void Main() {
         // Two arrays of type A[]
         A[] AArray1 = new A[3];
         A[] AArray2 = new A[3];
 
         // Normal--assigning objects of type A 
         // to an array of type A
         AArray1[0] = new A(); AArray1[1] = 
           new A(); AArray1[2] = new A();
 
         // Covariant--assigning objects of type B 
         // to an array of type A
         AArray2[0] = new B(); AArray2[1] 
            = new B(); AArray2[2] = new B();
      }
   }
Image:7230f1415.jpg
Arrays showing covariance
 
Note There is no covariance for value type arrays.
 
Useful Inherited Array Members
 
C# arrays are derived from class System.Array. From that base class, they inherit a number of useful properties and methods. Some of the most useful ones are listed in the given Table below:
 
Table: Some Useful Members Inherited by Arrays
 
Member ‘Type’ Lifetime Meaning
Rank Property Instance Gets the number of dimensions of the array
Length Property Instance Gets the total number of elements in all the dimensions of the array
GetLength Method Instance Returns the length of a particular dimension of the array
Clear Method Static Sets a range of elements to 0 or null
Sort Method Static Sorts the elements in a one-dimensional array
BinarySearch Method Static Searches a one-dimensional array for a value, using binary search
Clone Method Instance Performs a shallow copy of the array—copying only the elements, both for arrays of value types and refer¬ence types
IndexOf Method Static Returns the index of the first occurrence of a value in a one-dimensional array
Reverse Method Static Reverses the order of the elements of a range of a one- dimensional array
GetUpperBound Method Instance Gets the upper bound at the specified dimension
 
For example, the following code uses some of these properties and methods:
 
public static void PrintArray(int[] a)
   {
      foreach (int x in a) 
         Console.Write("{0}  ", x);
      Console.WriteLine("");
   }
 
   static void Main()
   {
      int[] arr = new int[] { 15, 20, 5, 25, 10 };
      PrintArray(arr);
      Array.Sort(arr);
      PrintArray(arr);
      Array.Reverse(arr);
      PrintArray(arr);
      
      Console.WriteLine
         ("Rank = {0}, Length = {1}",arr.Rank, arr.Length);
      Console.WriteLine("GetLength(0) = {0}",arr.GetLength(0));
      Console.WriteLine("GetType()    = {0}",arr.GetType());
   }
 
Clone Method
 
The Clone method performs a shadow copy of an array. This means that it only creates a clone of the array itself. If it is a reference type array, it does not copy the objects referenced by the elements. This has different results for value type arrays and reference type arrays.
 
• Cloning a value type array results in two independent arrays.

• Cloning a reference type array results in two arrays pointing at the same objects.

 
The Clone method returns a reference of type object, which must be cast to the array type.
 
  int[] intArr1 = { 1, 2, 3 };
  int[] intArr2 = ( int[] ) intArr1.Clone();
where: 
Array type = "int[]" 
Returns object "intArr1.Clone()" 
 
For example, the following code shows an example of cloning a value type array, producing two independent arrays. The given picture illustrates the steps followed by the code.
 
  static void Main()
  {
     // Step 1
     int[] intArr1 = { 1, 2, 3 };                             
     // Step 2
     int[] intArr2 = (int[]) intArr1.Clone();
     // Step 3
     intArr2[0] = 100; intArr2[1] = 200; intArr2[2] = 300;
  }
 
Image:7230f1416.jpg
Cloning a value type array produces two independent arrays.
 
Cloning is a reference type array results in two arrays pointing at the same objects. The following code shows an example. The given picture illustrates the steps followed by the code.
 
class A
   {
      public int Value = 5;
   }
 
   class Program
   {
      static void Main()
      {
         A[] AArray1 = new A[3] { new A(), new A(), new A() }; //Step 1
         A[] AArray2 = (A[]) AArray1.Clone();                  //Step 2
 
         AArray2[0].Value = 100;
         AArray2[1].Value = 200;
         AArray2[2].Value = 300;                               //Step 3
      }
   }
 
Image:7230f1417.jpg
Cloning a reference type array produces two arrays referencing the same objects
 
Comparing Array Types
 
Summarize some of the important similarities and differences between the three types of arrays.
 
Summary Comparing Array Types
 
Array Type Array Objects Syntax Brackets Syntax Commas Shape
One-dimensional–

Has optimizing instructions in CIL

1 Single set No Image:7230il1401.jpg
Rectangular–

Multidimensional– All sub-arrays in a multidimensional array must be the same length.

1 Single set Yes Image:7230il1402.jpg
Jagged–

Multidimensional– Sub-arrays can be of different lengths.

Multiple Multiple sets No Image:7230il1403.jpg
 
Understanding the Array Class
 
The Array class, defined in the System namespace, is the base class for arrays in C#. Array class is an abstract base class but it provides CreateInstance method to construct an array. The Array class provides methods for creating, manipulating, searching, and sorting arrays.
 
Table below describes Array class properties.
 
The System.Array Class Properties.
 
IsFixedSize Return a value indicating if an array has a fixed size or not.
IsReadOnly Returns a value indicating if an array is read-only or not.
IsSynchronized Returns a value indicating if access to an array is thread-safe or not.
Length Returns the total number of items in all the dimensions of an array.
Rank Returns the number of dimensions of an array.
SyncRoot Returns an object that can be used to synchronize access to the array.
 
Table below describes some of the Array class methods.
 
The System.Array Class Methods.
 
BinarySearch This method searches a one-dimensional sorted Array for a value, using a binary search algorithm.
Clear This method removes all items of an array and sets a range of items in the array to 0.
Clone This method creates a shallow copy of the Array.
Copy
  
This method copies a section of one Array to another Array and performs type casting and boxing as required.
CopyTo This method copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index.
CreateInstance This method initializes a new instance of the Array class.
GetEnumerator This method returns an IEnumerator for the Array.
GetLength This method returns the number of items in an Array.
GetLowerBound This method returns the lower bound of an Array.
GetUpperBound This method returns the upper bound of an Array.
GetValue This method returns the value of the specified item in an Array.
IndexOf This method returns the index of the first occurrence of a value in a one-dimensional Array or in a portion of the Array.
Initialize
 
This method initializes every item of the value-type Array by calling the default constructor of the value type.
LastIndexOf
  
This method returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array.
Reverse This method reverses the order of the items in a one-dimensional Array or in a portion of the Array.
SetValue This method sets the specified items in the current Array to the specified value.
Sort This method sorts the items in one-dimensional Array objects.
 
The Array Class
 
Array class is an abstract base class but it provides CreateInstance method to construct an array.
 
Array names = Array.CreateInstance( typeof(String), 2, 4 );
 
After creating an array using the CreateInstance method, you can use SetValue method to add items to an array. I will discuss SetValue method later in this chapter.
 
The Array class provides methods for creating, manipulating, searching, and sorting arrays. Array class provides three boolean properties IsFixedSize, IsReadOnly, and IsSynchronized to see if an array has fixed size, read only or synchronized or not respectively. The Length property of Array class returns the number of items in an array and the Rank property returns number of dimensions in a multi-dimension array.
 
In this example, we create two arrays with fixed and variable lengths and sends the output to the system console.
 
Example
 
int [] intArray;
 	// fixed array with 3 items
 	intArray = new int[3] {0, 1, 2};
 	// 2x2 varialbe length array
 	string[,] names = new string[,] { {"Rosy","Amy"}, {"Peter","Albert"} };
 	if(intArray.IsFixedSize)
 	{
 		Console.WriteLine("Array is fixed size");
 		Console.WriteLine("Size :" + intArray.Length.ToString());
 	}
 	if(names.IsFixedSize)
 	{
 		Console.WriteLine("Array is varialbe.");
 		Console.WriteLine("Size :" + names.Length.ToString());
 		Console.WriteLine("Rank :" + names.Rank.ToString());
 	} 
 
Besides these properties, the Array class provides methods to add, insert, delete, copy, binary search, reverse, reverse and so on.
 
Searching an Item in an Array
 
The BinarySearch static method of Array class can be used to search for an item in an array. This method uses binary search algorithm to search for an item. The method takes at least two parameters- an array and an object (the item you are looking for).
 
If an item found in an array, the method returns the index of the item (based on first item as 0th item) else method returns a negative value. The given code uses BinarySearch method to search two arrays.
 
Searching an item in an array through BinarySearch
 
int [] intArray = new int[3] {0, 1, 2};
 	string[] names = new string[] {"Rosy", "Amy", "Peter", "Albert" };
 	object obj1 = "Peter";
 	object obj2 = 1;
 	int retVal = Array.BinarySearch(names, obj1);
 	if(retVal >=0)
 		Console.WriteLine("Item index " +retVal.ToString() );
 	else 
 		Console.WriteLine("Item not found");
 	retVal = Array.BinarySearch(intArray, obj2);
 	if(retVal >=0)
 		Console.WriteLine("Item index " +retVal.ToString() );
 	else
 		Console.WriteLine("Item not found"); 
 
Sorting Item in an Array
 
The Sort static method of the Array class can be used to sort an array items. This method has many overloaded forms. The simplest form takes a parameter of the array, you want to sort to. The given code uses Sort method to sort an array items.
 
Sorting an array items
 
string[] names = new string[] {"Rosy", "Amy", "Peter", "Albert" };
 	Console.WriteLine("Original Array:");
 	foreach (string str in names)
 	{
 		Console.WriteLine(str);
 	}
 	Console.WriteLine("Sorted Array:");
 	Array.Sort(names);
 	foreach (string str in names)
 	{
 		Console.WriteLine(str);
 	} 
 
Getting and Setting Values in an Array
 
The GetValue and SetValue methods of the Array class can be used to return a value from an index of an array and set values of an array item at a specified index respectively. The code given below creates a 2-dimension array instance using the CreateInstance method.
 
After that I use SetValue method to add values to the array and at the end I find number of items in both dimensions and use GetValue method to read values and display on the console.
 
Using GetValue and SetValue methods
 
Array names = Array.CreateInstance( typeof(String), 2, 4 );
 	names.SetValue( "Rosy", 0, 0 );
 	names.SetValue( "Amy", 0, 1 );
 	names.SetValue( "Peter", 0, 2 );
 	names.SetValue( "Albert", 0, 3 );
 	names.SetValue( "Mel", 1, 0 );
 	names.SetValue( "Mongee", 1, 1 );
 	names.SetValue( "Luma", 1, 2 );
 	names.SetValue( "Lara", 1, 3 );
 	int items1 = names.GetLength(0); 
 	int items2 = names.GetLength(1);
 	for ( int i =0; i < items1; i++ )
 		for ( int j = 0; j < items2; j++ )
 			Console.WriteLine(i.ToString() +"
,"+ j.ToString() +": " +names.GetValue( i, j ) ); 
 
Other Methods of Array Class
 
The Reverse static method of the Array class reverses the order of items in an array. Similar to the sort method, you can just pass an array as a parameter of the Reverse method.
 
Array.Reverse(names);
 
The Clear static method of the Array class removes all items of an array and sets its length to zero. This method takes three parameters – first an array object, second starting index of the array and third is number of elements. The following code removes two elements from the array starting at index 1 (means second element of the array).
 
Array.Clear(names, 1, 2);
 
The GetLength method returns the number of items in an array. The GetLowerBound and GetUppperBound methods return the lower and upper bounds of an array respectively. All these three methods take at least a parameter, which is the index of the dimension of an array. The given code piece uses all three methods.
 
string[] names = new string[] { "Rosy", "Amy", "Peter", "Albert" };
 	Console.WriteLine(names.GetLength (0).ToString());
 	Console.WriteLine(names.GetLowerBound (0).ToString());
 	Console.WriteLine(names.GetUpperBound (0).ToString()); 
 
The Copy static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code given below is copies contents of an integer array to an array of object types.
 
Copying an array
 
	// Creates and initializes a new Array of type Int32.
 	Array oddArray = Array.CreateInsta
nce( Type.GetType("System.Int32"), 5 );
 	oddArray.SetValue (1, 0);
 	oddArray.SetValue (3, 1);
 	oddArray.SetValue (5, 2);
 	oddArray.SetValue (7, 3);
 	oddArray.SetValue (9, 4); 
 		// Creates and initializes a new Array of type Object.
 	Array objArray = Array.CreateInsta
nce( Type.GetType("System.Object"), 5 );
 	Array.Copy ( oddArray, oddArray.GetLowerBound(0), objArray, 
 	bjArray.GetLowerBound(0), 4 );
 	int items1 = objArray.GetUpperBound(0);
 	for ( int i =0; i < items1; i++ )
 		Console.WriteLine(objArray.GetValue(i).ToString());
 
You can even copy a part of an array to another array by passing number of items and starting item in the Copy method. The following format copies a range of items from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index.
 
public static void Copy(Array, int, Array, int, int);
 
To Download Arrays example Click here.
 
To view downloaded examples, Please Ensure that .NET Framework is installed on your system..
 
 

Check Also

Exceptions In C#

System.Exception is the base class for all other exceptions. Below this level are the System.ApplicationException …