Sunday, August 14, 2016

Using Arrays in C#

Arrays :


Arrays can be defined as a data structure for storing group of elements.
It can contain element of any data type. Following are examples of various
data types :

string[] strArray = new string[5];
int[] intArray = new int[3];
double[] dblArray = new double[4];
char[] charArray = new char[10];
bool[] boolArray = new bool[2];


Arrays can be of two types, fixed length (static) array and dynamic array.

Fixed arrays has predefined size. An example is :

int[] staticArray = new int[6];

Dynamic Arrays can store any number of items as it doesn't have a predefined
size. An example is :

int[] intArr;


Initialization and Accessing:


Arrays can be initialized in two ways :


int[] intArray= new int[3] {1, 2, 3};


or as follows :


int[] intArr= new int[3];
intArr[0] = 1;
intArr[1] = 2;
intArr[2] = 3;

Dynamic Array can be initialized as :


string[] strArr = new string[] { "Apple""Orange""Pears""Kiwi","Pomegranate" };

Values of array can be accessed as follows in ASP.NET :

Response.Write(strArr[1]) 

which will display the result as "Orange".

Using foreach Loop to access array elements :


Following is an example :

foreach (string str in strArray)
{
    Response.Write(str);
}

Array Types :


Arrays are of 4 different types :

(1) Single Dimensional :

These are arrays with one dimension as following examples :

int[] intArr = new int[4] {1, 2, 3, 4};
string[] names = new string[3] {"John", "Jerry", "Mary"};

(2) Multi Dimensional :

These are arrays with multiple dimensions as following examples :
int[,] intArr = new int[2, 3] { {1, 2, 3}, {3, 4, 5} };
string[,] strArr = new string[2, 2] { {"abc","def"}, {"ghi","jkl"} };
It can be used as a dynamic as follows :
int[,] intArr = new int[,] { {1, 2, 3}, {3, 4, 5} };
string[,] strArr = new string[,] { {"abc","def"}, {"ghi","jkl"} };

(3) Jagged Array :

These are array of arrays. Following is an example :
int[][] intArr= new int[2][] { new int[] {1,2,3}, new int[] {4,5} };

(4) Mixed Array :

It is a combination of multi dimension array and jagged array

Properties of Arrays :

It has many properties and commonly used one is Length and Rank.
Length contains total number of elements in all the dimensions of the array.
In this example :
string[] strArr = new string[] { "Apple""Orange""Pears""Kiwi","Pomegranate" };
Response.Write(strArr.Length);
will display the output as 5
Rank contains number of dimensions of the array
Response.Write(strArr.Rank);
will display the output as 1

No comments:

Post a Comment