C# Array Examples

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

Array elements

Every byte in your computer's memory is part of a single array. Abstractions translate these bytes into objects and give them meaning. Arrays in the .NET Framework are a foundational type. They are the basis of more usable collections, such as List and Dictionary. They use a special syntax form in the C# language.

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

Int array example

As an introduction to the C# array type, let's look at a simple example program that allocates and initializes an integer array of three elements. Please notice how the elements can be assigned to or read from using the same syntax (values[int]). The array is zero-based. We also demonstrate the foreach loop upon it.

Overview: The C# array type stores many elements of any type together. This page describes this useful type and provides examples.

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

Int array example 2

There is another way to allocate an array in your C# program and fill it with values. You can use the curly brackets { } to assign element values in one line. The length of the array is automatically determined when you compile your program.

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

Array for loop

For loop

Sometimes, it is useful to use the for-loop construct instead of the foreach-loop on your arrays. This is because it allows you to access the index value (i) as well as the element value in the array. For example, you could add logic that performs a different computation on the second element (where i == 1). The Length property is necessary here.

Program that uses for loop on int array [C#]

using System;

class Program
{
    static void Main()
    {
	// Create an 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 example

String type

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 Array
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

Array parameter example

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. Instead, just a reference to the array is copied when the new method is put on 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 array

Return keyword

Finally, you 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 of this method are printed to the screen.

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

2D arrays

Two-dimensional (2D)

The C# language offers two-dimensional and multidimensional arrays. These articles provide examples of 2D arrays and also a three-dimensional array. You can loop over 2D arrays or even use them with enumerators.

2D Array Examples 2D Array Loop Example Multidimensional Array

Jagged arrays

Jagged arrays are arrays of arrays. They can be faster or slower than 2D arrays based on how you use them. They can also require more or less memory, depending on the shape of your data.

Jagged Array Examples Jagged Versus 2D Array Memory

First element

The first element in an array in the C# language is at index 0. It can be accessed by using the indexer syntax, which has square brackets. Before acquiring this element, you should ensure that it can be accessed in the array region—you should usually test against null and test the Length in many cases.

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 element

You can use the array Length property to access the final element in an array. 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.

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

Types

We present examples of arrays used with different types available in the C# language. Additionally, we see examples of arrays that are static or null; these examples illustrate specific types of arrays.

Array type Bool Array Byte Array Char Array Enum Array Int Array Null Array Static Array Array Property Random Byte Array

ArraySegment

When you use arrays in your C# program, you will want to read or write into the elements with indexes. The ArraySegment type provides an abstraction for a part of an array. With the properties of ArraySegment, you can get the original array and also iterate through the specified range.

ArraySegment

Operations

Question and answer

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

Array Initializer Examples Combine Arrays Example Flatten Array Initialize Array

Methods

The Array type introduces many different methods you can use to effectively manipulate or test arrays and their elements. We cover specific methods and provide concrete examples for their usage.

Method call Array.AsReadOnly Array.BinarySearch Array.Clear Array.ConvertAll Array.Copy Array.CreateInstance Array.Exists Array.Find Array.FindIndex Array.ForEach Array.IndexOf Array.LastIndexOf Array.Resize Array.Reverse Array.Sort Array.TrueForAll

Properties

Property (Icon copyright Microsoft)

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.

Array Length Property Count Array Elements Array IsFixedSize, IsReadOnly and IsSynchronized

Buffer

The Buffer class provides a way to efficiently deal with bytes in large arrays. To start, this program introduces the Buffer type by using its BlockCopy method. The method call copies the first 12 bytes (three integers of four bytes each) of the source array (src) into the destination array (dst). You can see that the Buffer type acts upon bytes.

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

Buffer examples. More detailed information is available in the other Buffer articles on this site. With Buffer, you can improve performance and make some byte-level operations easier to handle. The most interesting article is about BlockCopy.

Buffer.BlockCopy Method Buffer.ByteLength Method Buffer.GetByte and Buffer.SetByte Methods

Performance

Performance optimization

Arrays are one of the low-level managed types in the C# language and .NET Framework. This means they will be faster than other structures such as List in many cases. In these articles, we dissect aspects of the array type's performance.

Array Optimization Tip Sentinel Element Locality of Reference

Misc.

Miscellaneous

There are more articles related to arrays on this site. They are supplementary and may be useful in certain situations.

Array Offset Example Country Name Arrays

Summary

The C# programming language

There is a lot of complexity to arrays in the C# language. Arrays are used at the core of many important types, such as the List or Dictionary types. A careful understanding of arrays will greatly improve the resilience and performance of your programs. This understanding is necessary for all C# programmers.

Dot Net Perls