C# Array

Array Class Collections File Keyword String .NET ASP.NET Cast Compression Data Delegate Directive Enum Exception If Interface LINQ Loop Method Number Process Property Regex Sort StringBuilder Struct Switch Time Windows WPF

Array

In abstraction,
our understanding,
our view of an object changes. Consider computer memory. It is an array of bytes. With abstraction, we understand these bytes to mean something. Arrays are a foundational type, a basis of many things.

Example

Let us start. This program allocates and initializes an integer array of three elements. Please notice how the elements are assigned, and read from, using the same syntax. The array is zero-based: the first element is element zero.

Expressions:An array element may be used in an expression. Here we multiply the values of the elements by 2 in expressions.

Program that uses an array: C#

using System;

class Program
{
    static void Main()
    {
	// Use an array.
	int[] values = new int[3];
	values[0] = 5;
	values[1] = values[0] * 2;
	values[2] = values[1] * 2;

	foreach (int value in values)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

5
10
20

Example 2

Programming tip

There is another way to allocate an array and fill it with values. We use curly brackets to assign element values in one line. This is concise. The length of the array is automatically determined by our friendly compiler.

Tip:This syntax causes no performance impact. It is compiled to the same code as the previous example.

Program that uses another array syntax: C#

using System;

class Program
{
    static void Main()
    {
	// Create an array of three ints.
	int[] array = { 10, 30, 50 };

	foreach (int value in array)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

10
30
50

For-loop

For loop

Sometimes it helps to use the for-loop construct instead of the foreach-loop on your arrays. This syntax allows you to access the index value (i) as well as the element value in the array. This can be helpful.

For example, you could add logic that performs a different computation on the second element (where i == 1). The Length property is necessary here. The for-loop is also helpful for comparing adjacent elements.

Program that uses for-loop on int array: C#

using System;

class Program
{
    static void Main()
    {
	// Array of three ints.
	int[] array = { 100, 300, 500 };

	// Use for loop.
	for (int i = 0; i < array.Length; i++)
	{
	    Console.WriteLine(array[i]);
	}
    }
}

Output

100
300
500

String array

String

Arrays are not just for value types such as ints. They can be used for strings and other object references (classes). An interesting point here is that the strings themselves are not stored in the array.

Rather:Just a reference to the string data is in the array. The strings are typically stored in the managed heap.

String Arrays
Program that creates string array: C#

using System;

class Program
{
    static void Main()
    {
	// Create string array of four references.
	string[] array = new string[4];
	array[0] = "DOT";
	array[1] = "NET";
	array[2] = "PERLS";
	array[3] = 2010.ToString();

	// Display.
	foreach (string value in array)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

DOT
NET
PERLS
2010

Parameter

Method call

How can you pass an array to another method to use there? This example program shows the correct syntax for passing an int array. Please note that the entire contents of the array are not copied.

Info:Just a reference to the array is copied when the new method is put in the call stack.

Program that receives array parameter: C#

using System;

class Program
{
    static void Main()
    {
	// Three-element array.
	int[] array = { -5, -6, -7 };
	// Pass array to Method.
	Console.WriteLine(Method(array));
    }

    /// <summary>
    /// Receive array parameter.
    /// </summary>
    static int Method(int[] array)
    {
	return array[0] * 2;
    }
}

Output

-10

Return

Return keyword

We can return arrays from methods. In this example program, we allocate a two-element array of strings in Method(). Then, after assigning its elements, we return it. In the Main method, the results are displayed.

Program that returns array reference: C#

using System;

class Program
{
    static void Main()
    {
	// Write array from Method.
	Console.WriteLine(string.Join(" ", Method()));
    }

    /// <summary>
    /// Return an array.
    /// </summary>
    static string[] Method()
    {
	string[] array = new string[2];
	array[0] = "THANK";
	array[1] = "YOU";
	return array;
    }
}

Output

THANK YOU

First

First

The first element is at index 0. It can be accessed by using the indexer syntax, which has square brackets. We first ensure that it can be accessed in the array region. We usually test against null and often test the Length.

Note:If we access an array element that does not exist, an IndexOutOfRangeException will occur.

Program that gets first array element: C#

using System;

class Program
{
    static void Main()
    {
	int[] array = new int[2]; // Create an array.
	array[0] = 10;
	array[1] = 20;

	Test(array);
	Test(null); // No output
	Test(new int[0]); // No output
    }

    static void Test(int[] array)
    {
	if (array != null &&
	    array.Length > 0)
	{
	    int first = array[0];
	    Console.WriteLine(first);
	}
    }
}

Output

10

Last

Programming tip

The last element's offset is equal to the array Length minus one. In many cases, you need to remember to check against null, and that the Length is greater than zero, before accessing the last element.

However:If you know an array access will succeed, there is no need to check the array length. Doing so will just slow the program down.

Program that gets last array element: C#

using System;

class Program
{
    static void Main()
    {
	string[] arr = new string[]
	{
	    "cat",
	    "dog",
	    "panther",
	    "tiger"
	};
	// Get the last string element.
	Console.WriteLine(arr[arr.Length - 1]);
    }
}

Output

tiger

2D array

2D array

The C# language offers two-dimensional and multidimensional arrays. We provide examples. We also loop over 2D arrays and use them with enumerators. There are some tricks to the syntax here.

2D Array

3D:If two dimension are not enough for you, try a three-dimensional array. Even further dimensions can be added.

Multidimensional Array

Caution:Multidimensional arrays are rarely ideal. Science fiction movies may find multiple dimensions more useful.

Jagged array

Framework: NET

Jagged arrays are arrays of arrays. They can be faster or slower than 2D arrays based on how they are used. They can also require more or less memory. This depends on the shape of your data.

Jagged Array

Memory:If you data is not rectangular (some rows are longer than others) a jagged array is ideal. It may even use less memory.

Jagged Array Memory

Types

Value

Arrays can be of any type. We can have (for example) bool, byte, int or char arrays. And all these arrays can also be used as static fields or properties. They can be null: this should be detected before an element access.

Bool ArrayByte ArrayChar ArrayEnum ArrayInt ArrayNull ArrayStatic Array

Property:An array property often benefits from special-casing.
We avoid returning null.

Array Property

Random:We can use the Random NextBytes method to fill a byte array with random values.

Random Byte Array

Operations

Plus

What should you do if you need to combine, flatten or initialize arrays in a certain way? These tutorials can help you out. They provide examples for these operations. Please also see the Buffer type.

InitializeCombineFlattenInitialize Array

Methods

The Array type introduces many methods. We use these methods to manipulate or test arrays and their elements. We cover specific methods. We use BinarySearch, for example, which optimizes searching a sorted array.

Array.AsReadOnlyArray.BinarySearchArray.ClearArray.ConstrainedCopyArray.ConvertAllArray.CopyArray.CreateInstanceArray.ExistsArray.FindArray.FindIndexArray.ForEachArray.IndexOfArray.LastIndexOfArray.ResizeArray.ReverseArray.SortArray.TrueForAll

Properties

Property

Continuing on, we examine properties on the Array type. The most commonly used property on arrays is the Length property, which is covered in detail here. We also describe the other boolean properties.

LengthIsFixedSize, IsReadOnly, IsSynchronized

Count:This is not an array property. But this extension method can be used to count elements, like the Length property.

Count Elements

ArraySegment

Steps

When we use arrays, we often want to read or write into the elements with indexes. ArraySegment helps here. It is an abstraction for part of an array. With its properties, we also access the original array.

ArraySegment

Buffer

Buffer

Buffer efficiently deals with bytes in large arrays. This program uses the Buffer.BlockCopy method. We copy the first 12 bytes (three integers of four bytes each) of the source array (src) into the destination array (dst).

Buffer

Tip:The Buffer type acts upon bytes, not array elements.
It is not helpful with object data.

Program that uses Buffer class: C#

using System;

class Program
{
    static void Main()
    {
	int[] src = { 1, 2, 3 };
	int[] dst = { 0, 0, 0 };
	Buffer.BlockCopy(src, 0, dst, 0, 3 * sizeof(int));
	foreach (int val in dst)
	{
	    Console.WriteLine(val);
	}
    }
}

Output

1
2
3

Performance

Performance optimization

Arrays are a low-level, managed type. They are faster than other structures, such as List, in many cases. This makes sense: the List is built with an internal array. We analyze the performance of arrays.

1. Avoid loops.We can sometimes avoid using a loop to store or load array elements. We simply assign indexes.

Optimization Tip

2. Use sentinels.A sentinel value in an array helps control the loop. It sometimes is used to reduce logical steps in a loop.

Sentinel Element

3. Improve locality.Array elements that are nearer together are faster to access. This principle is called "locality of reference."

Locality of Reference

4. Store expensive data.Static arrays can store expensive data in programs. For example, we store country names in an array.

Country Name Arrays

Research

Question and answer

What is an array? It is a collection of elements, all of a specific type. And these elements are stored together in memory. Each element is accessed by an integer index. This is the definition used in an algorithms textbook.

An array is a fixed collection of same-type data that are stored contiguously and that are accessible by an index. Sedgewick, p. 83

Arrays are the simplest and most common type of structured data. McConnell, p. 310

Summary

C# programming language

An array is a fixed region of memory that contains elements. Arrays are at once simple and complex. We find them at the core of important types: these include the List and Dictionary collections.

Therefore:An understanding of arrays will improve the quality of new programs. They will be more reliable and faster.

C#