An array is a data structure that can store a fixes sized collection of elements that belong to the same data type. For example, an array can store a sequence of numbers that starts from 1 to 10. Each item has an index that is represented by a number. For example:

  • arr [0] represents the 1st element of the array.
  • arr [5] represents the 6th element of the array.

To better understand this tutorial, you should know following C# programming areas:

Array in C#

Declaring and initializing an Array in C#

To declare an array, simply use the following syntax:

DataType [] StudentGPA;

Where datatype can be an integer, string, Boolean, etc. and the myArray is the Array name. Example:

double [] StudentGPA;
string [] StudentName;

 

Please note that declaring an array will not initialize it in the memory. So we need to use the new keyword to initialize and start assigning values to it. Example:

double [] StudentGPA = new double [10];

Where the number 10 represents the size of the array.

Array Types

Arrays are divided into the following four categories.

  • Single-dimensional arrays
  • Multidimensional arrays or rectangular arrays
  • Jagged arrays
  • Mixed arrays.

Assigning values to an Array

As mentioned above, the array index starts from zero [0]. So to assign a value to the first element in the array above, we need to use the following syntax.

StudentGPA[0] = 3.20;
StudentGPA[1] = 2.89;

Arrays can be assigned values at the time of declaration, for example:

double [] StudentGPA = { 3.2, 2.89, 1.90 };

Also, it can be declared and assigned values as a fixed length array:

double [] StudentGPA = new double [3] { 3.2, 2.89, 1.90 };

Or without size:

double [] StudentGPA = new double [] { 3.2, 2.89, 1.90 };

Array Methods:

There are too many array methods; however, we will cover the most important ones that every C# programmer should be aware of:

Clone

This methods creates a clone of the original array. It returns an exact length array.

string [] Arr1 = { "a", "b", "c" };
string [] Arr2 = (string[])Arr1.Clone();

CopyTo

CopyTo method copies the elements from an original one-dimensional array to a destination one-dimensional array starting from a specified destination. It adds an element to an already existing array. Example:

string[] Original = new string[1];
string[] destination = new string [1];
Original.CopyTo(destination , 0);

Exists

It determines whether an element matches the condition defined by a specified predicate. It returns “true” if an element exists, else returns false. Example:

int[] arrayA = new int[5];
int lengthA = arrayA.Length;
Console.WriteLine(lengthA); // returns 5

Length

Returns the total number of elements in an array. Example:

int[] arrayA = new int[5];
int lengthA = arrayA.Length;
Console.WriteLine(lengthA); // returns 5

Reverse

Reverses the ordering of a one-dimensional array’s elements. Example:

int[] array = { 1, 2, 3 };
Array.Reverse(array); // Reverse.

Sort

It sorts the elements in a one-dimensional array. Example:

// sort int array
int[] intArray = new int[5] { 8, 10, 2, 6, 3 };
Array.Sort(intArray); 

Assigning Array Elements:

However, a value can also be assigned to individual index randomly as shown below.

int[] intArray = new int[5];
intArray[0] = 10;
intArray[1] = 20;
intArray[2] = 30;
intArray[3] = 40;
intArray[4] = 50;

Accessing array elements:

int Array[0];  //returns 10
int Array[2];  //returns 30

Using the foreach Loop with Arrays.

Arrays are a powerful data structure that can help to simplify programming tasks. Using forech loop with arrays are among the most populate usage of an array in any computer system.

class Program
{
    static void Main()
    {
        string[] array = { "Arrays", "are", "powerful" };
 
        foreach (string term in array)
        {
            System.Console.WriteLine({ term } + “ “ ");
        }
    }
}

When the above code is compiled and executed, it produces the following result:

Arrays are powerful

Using for loop with arrays

This example is to use the “for loop” to irritate through arrays.

using System;

class Program
{
    static void Main()
    {
        string[] array = new string[2];
        array[0] = "Arrays";
        array[1] = "Are";
        arry[2] = "Powerfull";
        // Loop over array by indexes.
        for (int i = 0; i < array.Length; i++)
        {
            string element = array[i];
            Console.WriteLine(element);
        }
    }
}

Practical Example of arrays in C#

Array. IndexOf

IndexOf is used to search a one-dimensional array by value.

using System;

class Program
{
    static void Main()
    {
        string[] array = { "red", "blue", "green", "yellow" };

        // The blue string is at index 1.
        int blackIndex = Array.IndexOf(array, "blue");
        Console.WriteLine(blueIndex);

        // There is no black string in the array.
        // ... IndexOf will return -1.
        int blackIndex = Array.IndexOf(array, "black");
        Console.WriteLine(blackIndex);
    }
}

NOTE: IndexOf will return -1 in no element found.

Split and Join

using System;

class Program
{
    static void Main()
    {
        string[] elements = { "red", "blue", "green" };
        Console.WriteLine(elements[0]);

        // ... Join strings into a single string.
        string joined = string.Join("-", elements);
        Console.WriteLine(joined);

        // ... Separate joined strings with Split.
        string[] separated = joined.Split('-');
        Console.WriteLine(separated[0]);
    }
}

Sorting Items in an Array

The sort method is a used to sort array items. It’s a static method that has too many overloaded forms. The example below we will show you how to create an array, add items to it, find an object, then print original and sorted array.

// Create a String Array
Array strArray = Array.CreateInstance(typeof(String), 5);
strArray.SetValue("C", 0);
strArray.SetValue("F", 1);
strArray.SetValue("K", 2);
strArray.SetValue("A", 3);
strArray.SetValue("F", 4);

// Find an item A in the Array  
object name = "A";
int index = Array.BinarySearch(strArray, name);
if (index >= 0) Console.WriteLine("Item was at " + index.ToString() + "th position of the Array");
else Console.WriteLine("Item not found in Array");
// Print out Original Array
Console.WriteLine();
Console.WriteLine("Original Array:");
Console.WriteLine("---------------------");
foreach (string str in strArray)
{
    Console.WriteLine(str);
}
// Print out Sorted Array
Console.WriteLine();
Console.WriteLine("Sorted Array:");
Console.WriteLine("---------------------");
Array.Sort(strArray);
foreach (string str in strArray)
{
    Console.WriteLine(str);
}

Reverse elements in an Array

The Array.Reserve is another static method that reserve the order of elements in an Array. It takes the array as a parameter, as shown in the example below:

Array strArray = Array.CreateInstance(typeof(String), 5);
strArray.SetValue("A", 0);
strArray.SetValue("B", 1);
strArray.SetValue("C", 2);
strArray.SetValue("D", 3);
strArray.SetValue("E", 4);

//Print out original Array
Console.WriteLine("Original Array:");
Console.WriteLine("---------------------");
foreach (string strOriginal in strArray)
{
    Console.WriteLine(strOriginal);
}
//Print our reserved Array
Console.WriteLine();
Console.WriteLine("Reversed Array":);
Console.WriteLine("---------------------");
// reserve method
Array.Reverse(strArray);

foreach (string strReserved in strArray)
{
    Console.WriteLine(strReserved);
}

Clear elements in an Array

The Clear method is to clear array elements. The static method takes three arguments:  the Array to be cleared, the starting index of the array, and the number of items.  Please note that the Clear method will not delete the element of an Array. It only sets the value of the cleared element to the default value of its data type, which is an empty string in the example below:

 Array strArray = Array.CreateInstance(typeof(String), 5);
 strArray.SetValue("Cat", 0);
 strArray.SetValue("Dog", 1);
 strArray.SetValue("Fish", 2);
 strArray.SetValue("Snake", 3);
 strArray.SetValue("Bear", 4);
 Console.WriteLine("Original Array:");
 Console.WriteLine("---------------------");
 foreach (string strOriginal in strArray)
 {
 Console.WriteLine(strOriginal);
 }
 Console.WriteLine();
 Console.WriteLine("Clear Items:");
 Console.WriteLine("---------------------");
 Array.Clear(strArray, 1, 2);
 foreach (string strCleared in strArray)
 {
 Console.WriteLine(strCleared);
 }

Copy an Array

Another static method of the array class is Copy. It copies a section of an array to another Array. The code below is to copy the content of a string array to another array of object type:

// Creates and initializes a new Array of type string
Array strArray = Array.CreateInstance(typeof(string), 5);
strArray.SetValue("A", 0);
strArray.SetValue("B", 1);
strArray.SetValue("C", 2);
strArray.SetValue("D", 3);
strArray.SetValue("E", 4);
// Creates and initializes a new Array of type Object
Array objArray = Array.CreateInstance(Type.GetType("System.Object"), 5);
Array.Copy(strArray, strArray.GetLowerBound(0), objArray, objArray.GetLowerBound(0), 4);
int upperBound = objArray.GetUpperBound(0);
for (int i = 0; i < upperBound; i++)
{
    Console.WriteLine(objArray.GetValue(i).ToString());
}

 

Last modified: March 8, 2019

Comments

Write a Reply or Comment

Your email address will not be published.