You are on page 1of 16

Understanding C# Arrays

As I would guess you are already aware, an array is a set of data items, accessed using
a numerical index.
More specifically, an array is a set of contiguous data points of the same type (an array
of ints, an array of strings, an array of SportsCars, and so on). Declaring, filling, and
accessing an array with C# is quite straightforward. To illustrate, create a new Console
Application project (named FunWithArrays) that contains a helper method named
SimpleArrays(), invoked from within Main().
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Arrays *****");
SimpleArrays();
Console.ReadLine();
}
static void SimpleArrays()
{
Console.WriteLine("=> Simple Array Creation.");
// Create an array of ints containing 3 elements
//indexed 0, 1, 2
int[] myInts = new int[3];
// Create a 100 item string array, indexed 0 - 99
string[] booksOnDotNet = new string[100];
Console.WriteLine();
}
}
When declaring a C# array using this syntax, the number used in the array declaration
represents the total number of items, not the upper bound. Also note that the lower bound
of an array always begins at 0. Thus, when you write int[] myInts = new int[3], you end up
with an array holding three elements, indexed at positions 0, 1, 2.

1|Page
After you have defined an array variable, you are then able to fill the elements index by
index, as shown here in the updated SimpleArrays() method:
static void SimpleArrays()
{
Console.WriteLine("=> Simple Array Creation.");
// Create and fill an array of 3 Integers
int[] myInts = new int[3];
myInts[0] = 100;
myInts[1] = 200;
myInts[2] = 300;
// Now print each value.
foreach(int i in myInts)
Console.WriteLine(i);
Console.WriteLine();
}
Do be aware that if you declare an array but do not explicitly fill each index, each item will
be set to the default value of the data type (e.g., an array of bools will be set to false or
an array of ints will be set to 0).
C# Array Initialization Syntax
In addition to filling an array element by element, you are also able to fill the items of an
array using C# array initialization syntax. To do so, specify each array item within the
scope of curly brackets ({}). This syntax can be helpful when you are creating an array of
a known size and want to quickly specify the initial values. For example, consider the
following alternative array declarations:
static void ArrayInitialization()
{
Console.WriteLine("=> Array Initialization.");
// Array initialization syntax using the new keyword.
string[] stringArray = new string[]
{ "one", "two", "three" };

2|Page
Console.WriteLine("stringArray has {0} elements",
stringArray.Length);
// Array initialization syntax without using the new keyword.
bool[] boolArray = { false, false, true };
Console.WriteLine("boolArray has {0} elements",
boolArray.Length);
// Array initialization with new keyword and size.
int[] intArray = new int[4] { 20, 22, 23, 0 };
Console.WriteLine("intArray has {0} elements",
intArray.Length);
Console.WriteLine();
}
Notice that when you make use of this “curly-bracket” syntax, you do not need to specify
the size of the array (seen when constructing the stringArray variable), given that this will
be inferred by the number of items within the scope of the curly brackets. Also notice that
the use of the new keyword is optional (shown when constructing the boolArray type).
In the case of the intArray declaration, again recall the numeric value specified represents
the number of elements in the array, not the value of the upper bound. If there is a
mismatch between the declared size and the number of initializers (whether you have too
many or too few initializers), you are issued a compile-time error. The following is an
example:
// OOPS! Mismatch of size and elements!
int[] intArray = new int[2] { 20, 22, 23, 0 };
Implicitly Typed Local Arrays
The var keyword can be used to define implicitly typed local arrays. Using this technique,
you can allocate a new array variable without specifying the type contained within the
array itself (note you must use the new keyword when using this approach).
static void DeclareImplicitArrays()
{
Console.WriteLine("=> Implicit Array Initialization.");
// a is really int[].

3|Page
var a = new[] { 1, 10, 100, 1000 };
Console.WriteLine("a is a: {0}", a.ToString());
// b is really double[].
var b = new[] { 1, 1.5, 2, 2.5 };
Console.WriteLine("b is a: {0}", b.ToString());
// c is really string[].
var c = new[] { "hello", null, "world" };
Console.WriteLine("c is a: {0}", c.ToString());
Console.WriteLine();
}
Of course, just as when you allocate an array using explicit C# syntax, the items in the
array’s initialization list must be of the same underlying type (e.g., all ints, all strings, or
all SportsCars). Unlike what you might be expecting, an implicitly typed local array does
not default to System.Object; thus, the following generates a compile-time error:
// Error! Mixed types!
var d = new[] { 1, "one", 2, "two", false };
Defining an Array of Objects
In most cases, when you define an array, you do so by specifying the explicit type of item
that can be within the array variable. While this seems quite straightforward, there is one
notable twist. System.Object is the ultimate base class to every type (including
fundamental data types) in the .NET type system. Given this fact, if you were to define an
array of System.Object data types, the subitems could be anything at all. Consider the
following ArrayOfObjects() method (which again can be invoked from Main() for testing):
static void ArrayOfObjects()
{
Console.WriteLine("=> Array of Objects.");
// An array of objects can be anything at all.
object[] myObjects = new object[4];
myObjects[0] = 10;
myObjects[1] = false;
myObjects[2] = new DateTime(1969, 3, 24);

4|Page
myObjects[3] = "Form & Void";
foreach (object obj in myObjects)
{
// Print the type and value for each item in
array.
Console.WriteLine("Type: {0}, Value: {1}",
obj.GetType(), obj);
}
Console.WriteLine();
}
Here, as you are iterating over the contents of myObjects, you print the underlying type
of each item using the GetType() method of System.Object, as well as the value of the
current item.
Working with Multidimensional Arrays
C# also supports two varieties of multidimensional arrays. The first of these is termed a
rectangular array, which is simply an array of multiple dimensions, where each row is of
the same length. To declare and fill a multidimensional rectangular array, proceed as
follows:
static void RectMultidimensionalArray()
{
Console.WriteLine("=> Rectangular multidimensional
array.");
// A rectangular MD array.
int[,] myMatrix;
myMatrix = new int[3,4];
// Populate (3 * 4) array.
for(int i = 0; i < 3; i++)
for(int j = 0; j < 4; j++)
myMatrix[i, j] = i * j;
// Print (3 * 4) array.
for(int i = 0; i < 3; i++)

5|Page
{
for(int j = 0; j < 4; j++)
Console.Write(myMatrix[i, j] + "\t");
Console.WriteLine();
}
Console.WriteLine();
}
The second type of multidimensional array is termed a jagged array. As the name implies,
jagged arrays contain some number of inner arrays, each of which may have a different
upper limit. Here’s an example:
static void JaggedMultidimensionalArray()
{
Console.WriteLine("=> Jagged multidimensional
array.");
// A jagged MD array (i.e., an array of arrays).
// Here we have an array of 5 different arrays.
int[][] myJagArray = new int[5][];
// Create the jagged array.
for (int i = 0; i < myJagArray.Length; i++)
myJagArray[i] = new int[i + 7];
// Print each row (remember, each element is
defaulted to zero!).
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < myJagArray[i].Length; j++)
Console.Write(myJagArray[i][j] + " ");
Console.WriteLine();
}
Console.WriteLine();
}
The output of calling each of the RectMultidimensionalArray() and
JaggedMultidimensionalArray() methods within Main() is shown next:
6|Page
=> Rectangular multidimensional array:
0000
0123
0246
=> Jagged multidimensional array:
0000000
00000000
000000000
0000000000
00000000000
Arrays As Arguments or Return Values

After you have created an array, you are free to pass it as an argument or receive it as a
member return value. For example, the following PrintArray() method takes an incoming
array of ints and prints each member to the console, while the GetStringArray() method
populates an array of strings and returns it to the caller:
static void PrintArray(int[] myInts)
{
for(int i = 0; i < myInts.Length; i++)
Console.WriteLine("Item {0} is {1}", i,
myInts[i]);
}
static string[] GetStringArray()
{
string[] theStrings = {"Hello", "from",
"GetStringArray"};
return theStrings;
}
These methods may be invoked as you would expect:
static void PassAndReceiveArrays()
{
Console.WriteLine("=> Arrays as params and return

7|Page
values.");
// Pass array as parameter.
int[] ages = {20, 22, 23, 0} ;
PrintArray(ages);
// Get array as return value.
string[] strs = GetStringArray();
foreach(string s in strs)
Console.WriteLine(s);
Console.WriteLine();
}
At this point, you should feel comfortable with the process of defining, filling, and
examining the contents of a C# array variable. To complete the picture, let’s now examine
the role of the System.Array class.
The System.Array Base Class
Every array you create gathers much of its functionality from the System.Array class.
Using these common members, you are able to operate on an array using a consistent
object model.

8|Page
Select Members of System.Array

Let’s see some of these members in action. The following helper method makes use of
the static Reverse() and Clear() methods to pump out information about an array of string
types to the console:
static void SystemArrayFunctionality()
{
Console.WriteLine("=> Working with System.Array.");
// Initialize items at startup.
string[] gothicBands = {"Tones on Tail", "Bauhaus",
"Sisters of Mercy"};
// Print out names in declared order.
Console.WriteLine("-> Here is the array:");
for (int i = 0; i < gothicBands.Length; i++)
{
// Print a name.
Console.Write(gothicBands[i] + ", ");

9|Page
}
Console.WriteLine("\n");
// Reverse them...
Array.Reverse(gothicBands);
Console.WriteLine("-> The reversed array");
// ... and print them.
for (int i = 0; i < gothicBands.Length; i++)
{
// Print a name.
Console.Write(gothicBands[i] + ", ");
}
Console.WriteLine("\n");
// Clear out all but the first member.
Console.WriteLine("-> Cleared out all but one...");
Array.Clear(gothicBands, 1, 2);
for (int i = 0; i < gothicBands.Length; i++)
{
// Print a name.
Console.Write(gothicBands[i] + ", ");
}
Console.WriteLine();
}
If you invoke this method from within Main(), you will get the output shown
here:
=> Working with System.Array.
-> Here is the array:
Tones on Tail, Bauhaus, Sisters of Mercy,
-> The reversed array
Sisters of Mercy, Bauhaus, Tones on Tail,
-> Cleared out all but one...
Sisters of Mercy, , ,

10 | P a g e
Notice that many members of System.Array are defined as static members and are,
therefore, called at the class level (for example, the Array.Sort() and Array.Reverse()
methods). Methods such as these are passed in the array you want to process. Other
members of System.Array (such as the Length property) are bound at the object level;
thus, you are able to invoke the member directly on the array.

11 | P a g e
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FunWithArrays
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Arrays *****");
SimpleArrays();
ArrayInitialization();
DeclareImplicitArrays();
ArrayOfObjects();
RectMultidimensionalArray();
JaggedMultidimensionalArray();
PassAndReceiveArrays();
SystemArrayFunctionality();

Console.ReadLine();
}

#region Array declarations


static void SimpleArrays()
{
Console.WriteLine("=> Simple Array Creation.");
// Create and fill an array of 3 Integers
int[] myInts = new int[3];
myInts[0] = 100;
myInts[1] = 200;
myInts[2] = 300;

// Now print each value.


foreach (int i in myInts)
Console.WriteLine(i);
Console.WriteLine();
}

static void ArrayInitialization()


{
Console.WriteLine("=> Array Initialization.");

// Array initialization syntax using the new


keyword.

12 | P a g e
string[] stringArray = new string[] { "one", "two",
"three" };
Console.WriteLine("stringArray has {0} elements",
stringArray.Length);

// Array initialization syntax without using the new


keyword.
bool[] boolArray = { false, false, true };
Console.WriteLine("boolArray has {0} elements",
boolArray.Length);

// Array initialization with new keyword and size.


int[] intArray = new int[4] { 20, 22, 23, 0 };
Console.WriteLine("intArray has {0} elements",
intArray.Length);
Console.WriteLine();
}
#endregion

#region Implicitly typed arrays


static void DeclareImplicitArrays()
{
Console.WriteLine("=> Implicit Array
Initialization.");

// a is really int[].
var a = new[] { 1, 10, 100, 1000 };
Console.WriteLine("a is a: {0}", a.ToString());

// b is really double[].
var b = new[] { 1, 1.5, 2, 2.5 };
Console.WriteLine("b is a: {0}", b.ToString());

// c is really string[].
var c = new[] { "hello", null, "world" };
Console.WriteLine("c is a: {0}", c.ToString());
Console.WriteLine();
}
#endregion

#region Array of object types


static void ArrayOfObjects()
{
Console.WriteLine("=> Array of Objects.");

// An array of objects can be anything at all.


object[] myObjects = new object[4];

13 | P a g e
myObjects[0] = 10;
myObjects[1] = false;
myObjects[2] = new DateTime(1969, 3, 24);
myObjects[3] = "Form & Void";
foreach (object obj in myObjects)
{
// Print the type and value for each item in
array.
Console.WriteLine("Type: {0}, Value: {1}",
obj.GetType(), obj);
}
Console.WriteLine();
}
#endregion

#region multi-dimentional arrays


static void RectMultidimensionalArray()
{
Console.WriteLine("=> Rectangular multidimensional
array.");
// A rectangular MD array.
int[,] myMatrix;
myMatrix = new int[6, 6];

// Populate (6 * 6) array.
for (int i = 0; i < 6; i++)
for (int j = 0; j < 6; j++)
myMatrix[i, j] = i * j;

// Print (6 * 6) array.
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
Console.Write(myMatrix[i, j] + "\t");
Console.WriteLine();
}
Console.WriteLine();
}

static void JaggedMultidimensionalArray()


{
Console.WriteLine("=> Jagged multidimensional
array.");
// A jagged MD array (i.e., an array of arrays).
// Here we have an array of 5 different arrays.
int[][] myJagArray = new int[5][];

14 | P a g e
// Create the jagged array.
for (int i = 0; i < myJagArray.Length; i++)
myJagArray[i] = new int[i + 7];

// Print each row (remember, each element is


defaulted to zero!)
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < myJagArray[i].Length; j++)
Console.Write(myJagArray[i][j] + " ");
Console.WriteLine();
}
Console.WriteLine();
}
#endregion

#region Arrays as params and return values


static void PrintArray(int[] myInts)
{
for (int i = 0; i < myInts.Length; i++)
Console.WriteLine("Item {0} is {1}", i,
myInts[i]);
}

static string[] GetStringArray()


{
string[] theStrings = { "Hello", "from",
"GetStringArray" };
return theStrings;
}

static void PassAndReceiveArrays()


{
Console.WriteLine("=> Arrays as params and return
values.");
// Pass array as parameter.
int[] ages = { 20, 22, 23, 0 };
PrintArray(ages);

// Get array as return value.


string[] strs = GetStringArray();
foreach (string s in strs)
Console.WriteLine(s);

Console.WriteLine();
}
#endregion

15 | P a g e
#region System.Array functionality
static void SystemArrayFunctionality()
{
Console.WriteLine("=> Working with System.Array.");
// Initialize items at startup.
string[] gothicBands = { "Tones on Tail", "Bauhaus",
"Sisters of Mercy" };

// Print out names in declared order.


Console.WriteLine("-> Here is the array:");
for (int i = 0; i < gothicBands.Length; i++)
{
// Print a name
Console.Write(gothicBands[i] + ", ");
}
Console.WriteLine("\n");

// Reverse them...
Array.Reverse(gothicBands);
Console.WriteLine("-> The reversed array");
// ... and print them.
for (int i = 0; i < gothicBands.Length; i++)
{
// Print a name
Console.Write(gothicBands[i] + ", ");
}
Console.WriteLine("\n");

// Clear out all but the final member.


Console.WriteLine("-> Cleared out all but one...");
Array.Clear(gothicBands, 1, 2);
for (int i = 0; i < gothicBands.Length; i++)
{
// Print a name
Console.Write(gothicBands[i] + ", ");
}
Console.WriteLine();
}
#endregion
}
}

16 | P a g e

You might also like