“Chishiki” is Japanese for “knowledge.” e-chishiki.com aims to bring software developers, information security professionals, IT executives and other IT pros a rich body of knowledge in the form of articles, interviews, tutorials and technical discussions. Our contributors are among the biggest names in the Indian IT industry and include noted authors, educators and practitioners.
C# Programming Series
C# Arrays and Strings I
Yashavant Kanetkar
Arrays Defined
An array is a collection of similar elements stored in adjacent memory locations. These similar elements could be all ints, all floats, all chars, etc. For example,
int[] arr1 = { 1, 2, 3 } ;
float[] arr2 = { 1.5f, 2.5f, 3.5f } ;
char[] arr3 = { 'a', 'b', 'c' } ;
All elements of an array must be of the same type, i.e. we cannot have an array of 10 numbers, of which 5 are ints and 5 are floats. Arrays in C# are reference types and are implemented as objects. They are derived from the abstract class System.Array. The following code shows how to declare references to an int array:
int[ ] a ; // declare an int array reference int[ ] a1, a2 ; // declare two array references
Here a, a1, a2 are references to an int array. Thus we are not declaring an array. Instead, we are declaring a reference to it. This merely sets aside space for reference to an array. Once we have declared an array reference, we can construct an array through the statement:
a = new int [ 5 ] ;
Following figure shows how the array and reference would appear in memory:
To initialize an array we need to write the following statement:
int[ ] arr1 = new int[ ] { 3, 5, 7, 9, 1 } ;
Or
int[ ] arr1 = { 3, 5, 7, 9, 1 } ;
Here the array gets allocated on the heap and all its elements store a value. By default, all the elements of this array are initialized with a value 0. We can also create an array of objects. This is explained with an example,
sample[ ] s = new sample [ 5 ] ;
Here s is a reference to an array of references. The array gets created on the heap. Each element of the array in itself is a reference to the sample object. Hence, each reference would hold address of an object and not its value. By default, all the elements are initialized with a null reference. The in-memory view of the array is shown below:
To assign the array element with the addresses of the objects we need to write the following statements:
s [ 0 ] = new sample ( 1 ) ; s [ 1 ] = new sample ( 2 ) ; s [ 2 ] = new sample ( 3 ) ; s [ 3 ] = new sample ( 4 ) ; s [ 4 ] = new sample ( 5 ) ;
Or
sample s[ ] = {
new sample ( 1 ),
new sample ( 2 ),
new sample ( 3 ),
new sample ( 4 ),
new sample ( 5 ),
}Like C and C++, C# also uses a zero-based scheme to access array elements. This means that the first element in the array is considered to be at 0th position.
Multidimensional Arrays
In C# multidimensional arrays are of two types - Rectangular and Jagged. C# has a different syntax for both.



