Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C#

Learn step by step



Arrays in C#

What is array

Array is a type that holds multiple variables of one type, allowing index access to the individual value.

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

An array in .NET is created from Array base class. Array is a reference type because it is created from array class. The base class for arrays in C# is the System.Array class.

Array is fixed type. You can create array of primitive and non-primitive types. Array base address is stored in stack and array is kept in heap memory.

System.Array is the abstract base type of all array types. Array type can't be inherited. Array can't be extended. There size is fixed. Private constructor and inner class is use to create it.

Let's take a look at simple declarations of arrays in C#. The following code snippet defines the simplest dynamic array of integer types that does not have a fixed size.

int[] intArray;

As you can see from the above code snippet, the declaration of an array starts with a type of array followed by a square bracket ([]) and name of the array.

The following code snippet declares an array that can store 5 items only starting from index 0 to 4.

int[] intArray;
intArray = new int[5];

The following code snippet declares an array that can store 100 items starting from index 0 to 99.

int[] intArray;
intArray = new int[100];
Defining arrays of different types

In the previous code snippet, we saw how to define a simple array of integer type. Similarly, we can define arrays of any type such as double, character, and string.

In C#, arrays are objects. That means that declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator.

The following code snippet defines arrays of double, char, bool, and string data types.

double[] doubleArray = new double[5];
char[] charArray = new char[5];
bool[] boolArray = new bool[2];
string[] stringArray = new string[10];
Initializing Arrays

Once an array is declared, the next step is to initialize an array. The initialization process of an array includes adding actual data to the array.

The following code snippet creates an array of 3 items and values of these items are added when the array is initialized.

// Initialize a fixed array
int[] staticIntArray = new int[3] {1, 3, 5};

Alternative, we can also add array items one at a time as listed in the following code snippet.

// Initialize a fixed array one item at a time
int[] staticIntArray = new int[3];
staticIntArray[0] = 1;
staticIntArray[1] = 3;
staticIntArray[2] = 5;

The following code snippet declares a dynamic array with string values.


// Initialize a dynamic array items during declaration
string[] strArray = new string[] { "Mahesh Chand", "Mike Gold", "Raj Beniwal", "Praveen Kumar", "Dinesh Beniwal" };
Accessing Arrays

We can access an array item by passing the item index in the array. The following code snippet creates an array of three items and displays those items on the console.

// Initialize a fixed array one item at a time
int[] staticIntArray = new int[3];
staticIntArray[0] = 1;
staticIntArray[1] = 3;
staticIntArray[2] = 5;

// Read array items one by one
Console.WriteLine(staticIntArray[0]);
Console.WriteLine(staticIntArray[1]);
Console.WriteLine(staticIntArray[2]);
Type of Arrays in C#.NET

  • Single-dimensional arrays
  • Multidimensional arrays (rectangular arrays)
  • Jagged Arrays (array-of-arrays)
  • Mixed Arrays

Single Dimensional Array

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.

Single Dimensional array is also called one-dimensional array.


DataType[] VariableName = new DataType[Number];

  • In the above declaration DataType can be char, int, float, double, decimal, string, etc.
  • VariableName is the name of the array.
  • The square brackets [] on the left of the assignment operator are used to let the compiler know that you are declaring an array instead of a normal variable.
  • The new operator allows the compiler to reserve memory.
  • The [Number] factor is used to specify the number of items of the list.

Declaring single dimensional array

int[] arr = new int[10];

double numbers = new double[5];

string[] names = new string[2];

Single dimensional array initialization

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

string[] names = new string[] { "Rocky", "Sam", "Tina", "Yoo", "James", "Samantha" };

You can omit the size of the array, like this:

int[] numbers = new int[] {1, 2, 3, 4, 5};
string[] names = new string[] {"Reena", "Prety", "Rocky", "David");

You can also omit the new operator if you initialize array like this:

int[] numbers = {1, 2, 3, 4, 5};
string[] names = {"Reena", "Prety", "Rocky", "David"};

using System;

namespace array_example1
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[10];

for (int x = 0; x < 10; x++)
{
Console.WriteLine("Enter array element : {0}", x + 1);
arr[x] = Int32.Parse(Console.ReadLine());
}

foreach (int i in arr)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}

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

Multidimensional arrays (rectangular arrays)

Arrays can have more than one dimension; these arrays-of-arrays are called multidimensional arrays. They are very similar to standard arrays with the exception that they have multiple sets of square brackets after the array identifier.

The most common kind of multidimensional array is the two-dimensional array. A two dimensional array can be thought of as a grid of rows and columns.

Declaring multidimensional array

string[,] names = new string[4, 4];
int[,] numbers = new int[3, 4];

Multidimensional array initialization

int[,] numbers = new int[3, 2] {{1,2}, {3,4}, {5,6}};
string[,] names = new string[2, 2] {{"Ana", "Anita"}, {"Bob", "Barbie"}};

You can omit the size of the array, like this:

int[,] numbers = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[,] {{"Ana", "Anita"}, {"Bob", "Barbie"}};

You can also omit the new operator if you initialize array like this:

int[,] numbers = {{1,2}, {3,4}, {5,6}};
string[,] names = {{"Ana", "Anita"}, {"Bob", "Barbie"}};

using System;

namespace array_multidim
{
class Program
{
static void Main(string[] args)
{

//declaring a array with 4 rows and 3 columns
int[,] arr = new int[4, 3];

//accepting values in the array
for (int x = 0; x < 4; x++)
{
Console.WriteLine("Enter row element : {0}", x + 1);
for (int y = 0; y < 3; y++)
{
arr[x, y] = Int32.Parse(Console.ReadLine());
}
}

// displaying values of multidimensional array
for (int x = 0; x < 4; x++)
{
Console.WriteLine("Values of row : {0}", x + 1);

for (int y = 0; y < 3; y++)
{

Console.Write(arr[x, y] + "\t");
}
Console.WriteLine();
}

Console.ReadLine();
}
}
}
Jagged Arrays (array-of-arrays)

Jagged arrays are often called array of arrays. More specifically, a jagged array is an array of vectors. Unlike rectangular arrays, a jagged array, as the name implies, is jagged as each vector in the array can be of different length.

It is also possible to have jagged arrays, whereby "rows" may be different sizes. For this, you need an array in which each element is another array. However, all this is only possible if the arrays have the same base type.

Declaring and initializing jagged array.

int[][] jaggedArray = new int[2][];

jaggedArray[0] = new int[3];
jaggedArray[1] = new int[5];

jaggedArray[0] = new int[] { 3, 5, 7, };
jaggedArray[1] = new int[] { 1, 0, 2, 4, 6 };

You can also initialize the array upon declaration like this:

int[][] jaggedArray = new int[][]
{
new int[] { 3, 5, 7, },
new int[] { 1, 0, 2, 4, 6 }
};

You can use the following shorthand form:

int[][] jaggedArray =
{
new int[] { 3, 5, 7, },
new int[] { 1, 0, 2, 4, 6 }
};

Note: Notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements.

A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

It is possible to mix jagged and multidimensional arrays. The following is a declaration and initialization of a single-dimensional jagged array that contains two-dimensional array elements of different sizes:

int[][,] jaggedArray = new int[4][,]
{
new int[,] { {11,23}, {58,78} },
new int[,] { {50,62}, {45,65}, {85,15} },
new int[,] { {245,365}, {385,135} },
new int[,] { {1,2}, {4,4}, {4,5} }
};

using System;

namespace array_jagged
{
class Program
{
static void Main(string[] args)
{
// Declare the array of four elements:
int[][] arr = new int[4][];

// Initialize the elements:
arr[0] = new int[2] { 7, 9 };
arr[1] = new int[4] { 12, 42, 26, 38 };
arr[2] = new int[6] { 3, 5, 7, 9, 11, 13 };
arr[3] = new int[3] { 4, 6, 8 };

// Display the array elements:
for (int i = 0; i < arr.Length; i++)
{
System.Console.Write("Element({0}): ", i + 1);

for (int j = 0; j < arr[i].Length; j++)
{
System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " ");
}
System.Console.WriteLine();
}
Console.ReadLine();
}
}
}
Mixed Arrays

Mixed arrays are a combination of multi-dimension arrays and jagged arrays. Multi-dimension arrays are also called as rectangular arrays.

Understanding the Array Class

Arrays are extremely useful when you have several similar objects that you want to be able to process the same way or to be able to process as a group rather than individually.

The Array class, defined in the System namespace, is the base class for arrays in C#. Array class is an abstract base class, which can't be inherited, but it provides CreateInstance method to construct an array.

System.Array class provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime.

Array class properties

IsFixedSize Return a value indicating if an array has a fixed size 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.
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.
IndexOfThis 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.


Related Videos