Free Web Development Online Tutorials, Learn to Code
c# array declaration, c# array methods, Multidimensional Array C#, C# jagged arrays, c# an array of lists

C# Array Example

In this tutorial you will learn how to create C# Array and array methods like sort array, reverse array etc., also learn different between C# Array and ArrayList.

C# Array Declaration

In C# programming, we can declare different type of array like single-dimensional array, multidimensional array, and jagged arrays, here are some simple example.

Declare a single-dimensional array with fixed number, like following array can have only 10 elements.

int[] array1 = new int[10];

We also can define an array without setting the length at the time of declaration. Like in following array, you can add any number of elements.

int[] array2 = new int[]

We can also directly assign value at the time of declaration like this way.

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

Multidimensional Array C#

C# allows multidimensional arrays, here in example you learn how to decalre two-dimensional array and three-dimensional array in C#.

In following two-dimensional integer array we are storing five rows and two columns in each row.

int[,] twoDArray = new int[5, 2] {
{0, 10} , /* row 0 */
{1, 6} , /* row 1 */
{2, 47}, /* row 2 */
{3, 90}, /* row 3 */
{4, 91} /* row 5 */
};
for (int r = 0; r < 5; r++)
{
   int v1 = twoDArray[r, 0];
    int v2 = twoDArray[r, 1];
    Console.WriteLine("{0}, {1}", v1, v2);
}
Console.ReadKey();

When you execute the following code, following will be output.

0, 10
1, 6
2, 47
3, 90
4, 91

Here is another example of two-dimensional string array in c#.

We have five countries with their capital and language, so you can think of five rows and three columns in each row.

string[,] twoDArray1 = new string[,] {
{"India", "Delhi","Hindi"} , /* row 0 */
{"Srilanka","Colombo","Tamil"} , /* row 1 */
{"Bangaldesh","Dhaka","Bangla"}, /* row 2 */
{"United Kingdom","London","English"}, /* row 3 */
{"Germany","Berlin","German"} /* row 5 */
};
for (int r = 0; r < 5; r++)
{
    string v1 = twoDArray1[r, 0];
    string v2 = twoDArray1[r, 1];
    string v3 = twoDArray1[r, 2];
    Console.WriteLine("{0}, {1}, {2}", v1, v2, v3);
}
Console.ReadKey();

When you run the above code, you will see following result in console.

India, Delhi, Hindi
Srilanka, Colombo, Tamil
Bangaldesh, Dhaka, Bangla
United Kingdom, London, English
Germany, Berlin, German

c# jagged arrays example

Jagged array is basically array of arrays, each element in a Jagged array is also an array, now each element (array) can be of different dimensions and sizes.

This is how we can declare a jagged array, example of declaring a single-dimensional array with four elements

int[][] jaggedArray1 = new int[4][];

Before we can use any jaggedArray, we must initialize the array.

As you can see in example below, each jaggedArray element (array) has different length of array.

int[][] jaggedArray1 = new int[4][];

jaggedArray1[0] = new int[2] { 100, 180};
jaggedArray1[1] = new int[4] { 40,50,70,99};
jaggedArray1[2] = new int[3] { 12,25,65};
jaggedArray1[3] = new int[5] { 4,9,3,8,7};

C# Array and ArrayList

Array and ArrayList both are used to store collection of object, but there are some different, in real-time application development you come across situation where you need to decide which one to use, both are very useful.

What is an Array in C#?
An Array is a strongly-typed collection that store a series of elements same type

using system;
public abstract class Array : ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
Integer Array c# example

this is how you initialize an integer array and add item to an Array.
C# Arrays initialization and c# array add item example

int[] myArray=new int[]{5};
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;

There is another alternate way of creating integer array, you can create a list object, then add item to list object, and finally you can get an array just by converting list to array

List to Array Example
List<int> objInList = new List<int>();
objInList.Add(10);
objInList.Add(15);
objInList.Add(18);
objInList.Add(21);
objInList.Add(32);

int[] intArray = objInList.ToArray();
String Array C# Example

this is how you initialize an string array.
C# array add new item : adding new item to string Array

string[] myArray=new string[4];
myArray[0] = "Red";
myArray[1] = "White";
myArray[2] = "Green";
myArray[3] = "Blue";

To read values from an Array, you can simply use the index number or you can loop through array object.

string _value = myArray[2]; 

// OR
foreach (string s in myArray)
{
    Console.WriteLine(s);
}

As you can see in above int or string array we could add only that particular data type like int or string.

C# Array Methods Example

Here are some important methods of System.Array class

  • Copy(Array,Array,Int32)

    Copy elements of an array into another array by specifying starting index

  • CopyTo(Array,Int32)

    Copies all the elements of the current one-dimensional array to the specified one-dimensional array

  • Clone()

    Copy array structure without data, Create a shallow copy of the Array

  • Reverse(Array)

    Reverse the sequence of the elements in the entire one-dimensional Array

    Here is an example of string array Reverse method in c#

    string[] myArray = new string[4] ;
    myArray[0] = "Red";
    myArray[1] = "White";
    myArray[2] = "Green";
    myArray[3] = "Blue";
    Array.Reverse(myArray);
    foreach (string s in myArray)
    {
        Console.WriteLine(s);
    }
  • Sort(Array): Sort an Array

    Sort the elements in an entire one-dimensional Array

    Here is an example of string array Sort method in c#

    string[] myArray = new string[4] ;
    myArray[0] = "Red";
    myArray[1] = "White";
    myArray[2] = "Green";
    myArray[3] = "Blue";
    Array.Sort(myArray);
    foreach (string s in myArray)
    {
        Console.WriteLine(s);
    }
    
C# Array Properties
  • Length

    Get the total number of elements in that Array

  • IsFixedSize

    Get bool value indicating whether the Array has a fixed size or not.

  • IsReadOnly

    Boolean value indicates if the Array is read-only

What is an ArrayList in C#?

An ArrayList is not a strongly-typed collection. It can store the values of different data types or same data type. The size of an array list can increases or decreases dynamically, it can take any size of values from any data type.

ArrayList myArrayList = new ArrayList();
myArrayList.Add(1);
myArrayList.Add("this is string");
myArrayList.Add(1.2);
myArrayList.Add(DateTime.Now);

As you can see in above ArrayList we have added different data types integer, string, decimal, date etc

equilibrium index of an array

Sum of elements at lower indexes = Sum of elements at higher indexes.

int[] arr = { -9, 2, 5, 4, -2, 3, -3 };

3 is an equilibrium index of above array, because

arr[0] + arr[1] + arr[2] = arr[4] + arr[5] + arr[6]

Third element of the array arr[3] which is the balance point of both side of the array.

Here is how you can find equilibrium index of an array!

int getEquilibriumIndex(int[] arr)
{
int arrLength= arr.Length;
int i, j;
int leftSum, rightSum;
for (i = 0; i < arrLength; ++i)
{
leftSum = 0;
rightSum = 0;
for (j = 0; j < i; j++)
{
leftSum += arr[j];
}
for (j = i + 1; j < arrLength; j++)
        {
            rightSum += arr[j];
        }


        if (leftSum == rightSum)
            return i;
    }

    return -1;
}


// Calling the function.
int[] arr = { -9, 2, 5, 4, -2, 3, -3 };
int result = getEquilibriumIndex(arr);

Difference between C# Array and ArrayList

C# Array C# ArrayList
Arrays belong to System.Array namespace using System; Arraylist belongs to System.Collection namespaces using System.Collections;
In Array, we can store only one datatype either int, char, string etc In Arraylist, we can store different datatype values
Array cant accept null ArrayList collection accepts null
Comment
Name
Email
Website
Subscribe
 
free C# tutorial online


Create C# Array
Other Online Tutorial

C# .net Interview Questions Answers

.Net C# Examples | Join .Net C# Course