You are here:   HomeC# ProgrammingIntroduction to C#Type of Array
by Dinesh Thakur Category: Introduction to C#

An array is a group or collection of similar type of elements.

 

An array is a group or collection of similar values. An array contains a number of variables, which are accessed through computed indexes. The various value contained in an array are also called the elements of array. All elements of an array have to be of same type, and this type is called the element type of the array. The element of an array can be of any type including an array type.

An array has a rank that determines the number of indexes associated with each array elements. The rank of an array is also referred as the dimension of the array. An array may be:

 

• Single Dimensional

• Multi Dimensional



An array with a rank of one is called single-dimensional array, and an array with a rank greater than one is called a multi dimensional array.

 

Each dimension of array has an associated length, which is an integer number greater than or equal to zero. For a dimension of length n, indices can range from 0 to n-l. In C#, array types are categorized under the reference types derived from. the abstract base. Types system. Array.

Single Dimensional Array

Single-dimensional arrays have a single dimension (ie. are of rank 1). The process of creation of arrays is basically divided into three steps:

 

1. Declaration of Array

2. Memory Allocation for Array

3. Initialization of Array

 

Declaration of Array

 

To declare an array in C# place a pair of square brackets after the variable type. The syntax is given below :

 

type[] arrayname;

For Example:

 

int [ ] a;

float[] marks;

double] x;

int [ ] m, n ;

You must note that we do not enter the size of the arrays in the declaration.

 

Memory Allocation for Array

 

After declaring an array, we need to allocate space and define the size. Declaring arrays merely says what kind of values the array will hold. It does not create them. Arrays in C# are objects, and you use the new keyword to create them. When you create an array, you must tell the compiler how many components will be stored in it. Here is given the syntax:

 

arrayname = new type[size];

 

For Example:

 

a = new int[5];

marks = new float[6];

x = new double[10];

m = int[100];

n = int [50];

It is also possible to combine the two steps, declaration and memory allocation of array, into one as shown below:

 

int[] num= new int [5];

 

Initialization of Array

 

This step involves placing data into the array. Arrays are automatically assigned the default values associated with their type. For example, if we have an array of numerical type, each element is set to number o. But explicit values can be assigned as and when desired.

Individual elements of an array are referenced by the array name and a number that represents their position in the array. The number you use to' identify them are called subscripts or indexes into the array.

Subscripts are consecutive integers, beginning with 0. Thus the array "num" above has components num[0], num[l], num[2], num[3], and num[4].

The initialization process is done using the array subscripts as shown:

 

arrayname[subscript] = value;

 

For Example:

 

num[O] = 5;

num[1] = 15;

num[2] = 52;

num[3]·= 45;

num[4] = 157;

We can also initialize arrays automatically in the same way as the ordinary variables when they are declared, as shown below:

 

type[] arrayname = { list of values };

the list of variables separated by commas and defined on both ends by curly braces. You must note that no size is given in this syntax. The compiler space for all the elements specified in the list.

For Example:

 

int[] num = {5,15,S2,45,57};

You can combine all the steps, namely declaration, memory allocation and initialization of arrays like as: ",

 

int[] num = new int [5]" {5,15,52,4S,S7};

You-can also assign an array object to another. For Example

 

int [] a = { 10, 20, 30};

int [] b;

b=a;

The above example is valid in C#. Both the array will have same values.

Demonstration of array

using system;

class Number

{

public static void Main()

{

int [] num = {10, 20, 30, 40, SO};

int n =. num.Length;

II Length is predefined attribute to access the size of array

console.write(" Elements of ,array are :");

for(int ;=0; i<n; i++)

{

console.writeLlne(num[i]);

}

int sum =0;

for(int i=O; i<n; i++) {

sum = sum +.num[i]); }

Console.writeLine(" The sum of elements :"+sum);

}

OUTPUT:

Elements of array are:

10

20

30

40

50

 

The sum of elements :150

Note : If you do not initialize an array at the time of declaration, the array members are automatically initilized 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.

Multi Dimensional Array

C# supports two types of multidimensional arrays:

 

• Rectangular Array

• Jagged Array

 

Rectangular Arrays

 

A rectangular array is a single array with more than one dimension, with the dimensions' sizes fixed the array's declaration. The following code creates a 2 by 3 multi-dimensional array:

 

int[,] squareArray =new int[2,3];

As with single-dimensional arrays, rectangular· arrays can he filled at the time they are declared. For instance, the code

 

int[,] squareArray = {{l, 2, 3}, {4 , 5, 6}};

 

creates a 2 by 3 array with the given values . .It is, of course, important that the given values do fill out exactly a rectangular array.

The System.Array class includes a number of methods for determining the size and bounds of arrays. These include' the methods GetUpperBound(int i) and GetLowerBound(int i), which return, ;respectively, the upper and lower subscripts of dimension i of the array (note that i is zero based, so the first array is actually array 0).

For instance, since the length of the second dimension of squareArray is 3, the expression

 

squareArray.GetLowerBound(l)

returns 0, and the expression

 

squareArray.GetupperBound(l)

returns 2, because lowerbound is 0 and upperbound is 2 for length 3.

System.Array also includes the method GetLength(int i), which returns the number of elements in the ith dimension (again, zero based) ..

The following piece of code loops through squareArray and writes out the value of its elements.

 

for(int i = 0; i < squareArray.GetLengthCO); i++)

for (int j = 0; j < squareArray.GetLengthCl); j++)

console.writeLine(squareArray[i,j]);

A foreach loop can also be used to access each of the elements of an array in turn, but using this construction one doesn't have the same control over the order in which the elements are accessed.

 

Jagged Arrays

 

A jagged array is an array whose elements are arrays. The elements can be different dimensions and sizes.

Using jagged arrays, one can create multidimensional arrays with irregular dimensions. This flexibility derives from the fact that multidimensional arrays are implemented as arrays of arrays. The following piece of code demonstrates how one might declare an array made up of a group of 4 and a group of 6 elements:

 

int[][] jag = new int[2][];

jag[0] = new int [4];

jag[l] = new int [6];

 

The code reveals that each of jag[O] and jag[l] holds a reference to a single-dimensional int array. 'To illustrate how one accesses the integer elements: the termjag[0] [1] provides access to the second element of the first group.

& Concept

To initialise a jagged array whilst assigning values to its elements, one can use code like the following:

 

int[ ][ ] jag = new int[ ][ ] {new int[ ] {1, 2, 3, 4}, new int[ ] {5, 6, 7, 8, 9, 10}};

 

Be careful using methods like GetLowerBound, GetUpperBound, GetLength, etc. with jagged arrays. Since jagged arrays are constructed out of single-dimensional arrays, they shouldn't be treated as having multiple dimensions in the same way that rectangular arrays do.

 

To loop through all the elements of a jagged array one can use code .like the following:

 

for (int i = 0; i < jag.GetLength(O); i++)

for (int j = 0; j < jag[i].GetLength(O); j++)

console.writeLine(jag[i] [j]);

 

or

 

for (int i = 0; i < jag.Length; 'i++)

for (int j = 0; j < jag[i].Length; j++)

console.writeLine(jag[i] [j]);

 

The following example builds on arrays myArray, whose elements are arrays. Each one of array elements has a different size.

 

using System;

public class Array Test

{

public static void Main()

{

II Declare the array of two elements

int [][] myArray = new int [2][];

II initilize the elements

myArray [0] = new int [5] {I, 3, 5, 7, 9};

myArray [1] = new int [4] {2, 4, 6, 8};

II Display the array elements

 

for (int i = 0; i< myArray.Length; i++)

{

console.write ("Element( {O}):", i)

for (int j = 0; j < myArray [i].Length; j++)

console.write ("{O}", myArray [i] [j]);

console.writeLine ();

}

}

}

 

OUTPUT:

 

Element (0): 1 3 5 7 9

Element (1): 2 4 6 8

Passing Arrays as Parameters

You can pass an initialized array to a method. Here we given example of a printArray (myArray); function for both single and multidimensional arrays.

Single Dimension

In following example, a string array is initialized and passed as a parameter to the printArray method, where its elements are displayed.

 

using System;

public class Arrayclass

{

static void PrintArray (string [] w)

{

for (int i = 0; i < w.Length; i++)

console.write (w[i]);

Console.writeline ();

}

public static void Main ()

{

II Declare and initialize an array

string [] weekDays = new string []

{"sun", "Sat", "Mon", "Tue", "wed", "Thu", "Fri"};

1/ Pass the array as a parameter

printArray (weekDays);

}

}

 

OUTPUT:

 

Sun Sat Mon Tue wed Thu Fri

Multi Dimension

In this example, a two dimensional array is initialized and passed to the PrintArray method, where its elements are displayed.

 

using system;

public class Arrayclass

{

static void printArray (int [,]w)

{

II Display the array elements

for (int i = 0; i < 4; i++)

for (int j = 0; j < 2; j++)

console.writeLine ("Element {O}; {1} = {2}", i, j,w[i ,j]);

}

public static void Main ()

{

II pass the array as a parameter

printArray (new int [,] {{1, 2}, {3, 4}, {5, 6}, {7, 8}});

}

}

OUTPUT:

 

Element (0, 0) =1

Element (0, 1) = 2

Element (1, 0) = 3

Element (1, 1) = 4

Element (2,    0) = 5

Element (2,   1) = 6

Element (3,    0) = 7

Element (3,   1) = 8





Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular





Search Content







Advance Courses



Basic Courses



Advertise with Us