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

Arrays. 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.


Elements

A foundation. Arrays are a foundational type, a basis of many things.
With a number,
an index,
we access a unit of data. The meaning of this connection is part of our abstraction.


Three

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.

Zero:The array is zero-based.
The first element is element zero.
Element indexes proceed upwards by one.

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

Syntax

Initialization. This syntax form is shorter. We use curly brackets to assign element values in one line. This is concise. The length of the array is automatically determined.

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

Loop

For-loop. Sometimes it helps to use the for-loop construct on an array. This syntax allows us to access the index value (i). We also read the element value in the array.

Tip:We could perform a different computation on the second element (where i == 1). The Length property is necessary here.

Further:The for-loop is also helps compare adjacent elements. We can add one or subtract one to get these.

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

Strings. Arrays are not just for value types such as ints. They are used for strings and other object references (classes). 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

Method call

Parameter. How can we pass an array to another method to use there? Here is the correct syntax for passing an int array. The entire contents of the array are not copied.

Instead: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 keyword

Return. 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.

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.

Usually:We test against null.
Often we test the Length.
An error occurs if we go out of range.

Note:This error is an IndexOutOfRangeException. An element can be null, but this is still in range and no error 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

Programming tip

Last. The last element's offset is equal to the array Length minus one. Often we need to check against null, and that the Length is greater than zero, before accessing the last element.

However:If we 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 also loop over 2D arrays. We use them with enumerators.

2D Array

3D:If two dimension are not enough, 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.


Program

Jagged arrays are arrays of arrays.
They can be faster,
or slower,
than 2D arrays based on usage. The memory required too varies. This depends on the shape of data.

Jagged Array

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

Jagged Array Memory
Value

Types. 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.

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
Plus

Operations. Suppose two arrays exist. We can combine them. Suppose a 2D array is present. We can flatten it into a single array. An array can operated upon in nearly any way imaginable.

InitializeCombineFlattenInitialize Array

Methods. The Array type introduces many methods. We use these methods to manipulate or test arrays and their elements. We use BinarySearch—this optimizes searching a sorted array.

AsReadOnlyBinarySearchClearConstrainedCopyConvertAllCopyCreateInstanceExistsFindFindIndexForEachIndexOfLastIndexOfResizeReverseSortTrueForAll
Property

Properties. The most commonly used property on arrays is the Length property.
With Length,
we access a stored field,
and no costly counting occurs. Length has no internal loops.

Length

IsFixedSize:An array has many boolean properties.
These are rarely useful.
But I like to be thorough.

IsFixedSize, 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
Steps

ArraySegment. 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.

ArraySegment
Concept

Buffer deals with bytes in large arrays. It is fast. This program uses BlockCopy. We copy the first 12 bytes (three ints of 4 bytes each) of the source array into the destination array.

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 optimization

Performance. 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.

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
String face

Research. What is an array? An array 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.

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


ABC: letters

In understanding arrays, all parts of our programs can be improved. Programs become more reliable and faster. Arrays are everywhere, buried within other types.


Levels. On abstraction's ladder,
arrays are closer to the machine,
less abstract,
than many objects. But they are key to adding abstraction and building complexity in programs.


Array type

An array is a fixed region of memory that contains elements. Arrays are at once simple and complex. And we find them at the core of important types, like List and Dictionary.

C#