How To Initialize C# Arrays

How To Initialize Arrays Banner Image

Introduction

C# offers a variety of ways to initialize an array. Some just initialize to default values or null. Depending if the object is a value or reference type then the default value is different. Some allow you to initialize to specific values. There are also short-hand and long-hand ways. These have accumulated over the years and Microsoft has not pruned them. Let's start with the most basic and simple forms and then work our way to the more complex examples.

Initialize An Array To Null Or Default Values

This example shows how the most common types behave. Strings and classes are initialized to null. Double, int and float are initialized to zero. Bool is initialized to false. This kind of initialization is common in arrays. Later we usually plan to assign it with more meaningful data or just load it with the target data. But as you can see with strings and class you'll have to be careful because since they are populated with null you'll either need to add null checks later in the code or just populate these right away with non-null values.

//All strings are initialized to null
string[] stringArray = new string[3];//Allocates an string array of size 3

//Classes are initialized to null
Car[] classArray = new Car[3];//Allocates an car array of size 3

//Value types are initialized to 0
double[] doubleArray = new double[3];//Allocates an double array of size 3
int[] intArray = new int[3];//Allocates an int array of size 3
float[] floatArray = new float[3];//Allocates an float array of size 3

//Bool will be set to false by default
bool[] boolArray = new bool[3];//Allocates an bool array of size 3

PrintArrayValues<double>(doubleArray, "doubleArray");
PrintArrayValues<int>(intArray, "intArray");
PrintArrayValues<float>(floatArray, "floatArray");
PrintArrayValues<bool>(boolArray, "bool");

void PrintArrayValues<T>(T[] array, string ArrayName)
{
    Console.WriteLine($"{ArrayName}:" + string.Join(",", array));
}

class Car
{
    public int WheelCount { get; set; }
    public int TopSpeed { get; set; }
    public string Type { get; set; }
}

Code Output
doubleArray:0,0,0
intArray:0,0,0
floatArray:0,0,0
boolArray:False,False,False
More Info On Empty Array Initializers

If you want to know more about how to initialize an empty array. I wrote an article Best Initializer To Get An Empty Array that talks all about the details of creating empty arrays.

Initialize An Array With An Array Initializer

In the previous example,the string and the Car class I created were null. But now I want to initialize them to certain values of my choosing. The following example shows all the previous objects will now have a set value. I can do this by using the array initializer. This syntax uses two enclosing curly braces with each separated by a comma.

//All strings are initialized to book titles
string[] stringArray = new string[3] { "To Kill a Mockingbird", "The Catcher in the Rye", "The Lord of the Rings" };//Allocates a string array of size 3 with 3 book titles

//Classes are initialized to values
Car[] classArray = new Car[3] { new Car(4, 200, "sedan"), new Car(4, 140, "truck"), new Car(4, 180, "SUV") };//Allocates a car array of size 3 with 3 car values

//Value types are initialized to 0
double[] doubleArray = new double[3] { 39.3, 218.38, 480.934 };//Allocates an double array of size 3
int[] intArray = new int[3] { 4, 108, 302 };//Allocates an int array of size 3
float[] floatArray = new float[3] { 32f, 3230f, 32.323f };//Allocates an float array of size 3

//Bool will be set to false by default
bool[] boolArray = new bool[3] { true, false, true };//Allocates an bool array of size 3

PrintArrayValues<string>(stringArray, "stringArray");
PrintArrayValues<Car>(classArray, "classArray");
PrintArrayValues<double>(doubleArray, "doubleArray");
PrintArrayValues<int>(intArray, "intArray");
PrintArrayValues<float>(floatArray, "floatArray");
PrintArrayValues<bool>(boolArray, "boolArray");

void PrintArrayValues<T>(T[] array, string ArrayName)
{
    Console.WriteLine($"{ArrayName}:" + string.Join(",", array));
}

class Car
{
    public Car(int wheelCount, int topSpeed, string type)
    {
        WheelCount = wheelCount;
        TopSpeed = topSpeed;
        Type = type;
    }

    public int WheelCount { get; set; }
    public int TopSpeed { get; set; }
    public string Type { get; set; }

    public override string? ToString()
    {
        return $"WheelCount:{WheelCount}, TopSpeed:{TopSpeed}, Type:{Type}".ToString();
    }
}
Code Output
stringArray:To Kill a Mockingbird,The Catcher in the Rye,The Lord of the Rings
classArray:WheelCount:4, TopSpeed:200, Type:sedan,WheelCount:4, TopSpeed:140, Type:truck,WheelCount:4, TopSpeed:180, Type:SUV
doubleArray:39.3,218.38,480.934
intArray:4,108,302
floatArray:32,3230,32.323
boolArray:True,False,True
More Info On Non Empty Array Initializers

If you want more details on how to automatically populate large sized array with values then check out the following blog post: Fill The Array With One Value

C# Programming for Unity Game Development Specialization

COURSERA

C# Programming for Unity Game Development Specialization

4.7 (2,230 reviews)

Beginner level

No previous experience is necessary

3-months at 10 hours a week (At your pace)

$59 / month or audit, and financial aid available

If you want to learn more about C# then check out this course on Coursera. It's a 3 month course to take you through the basics of C#.

You can get started with programming using C# and apply it to Unity games in this beginner-level program. Facilitated by the University of Colorado, the program offers a chance to grasp the basics of C# and utilize the knowledge to develop Unity games.

[Full Disclosure: As an affiliate, I receive compensation if you purchase through this link]

Start Your 7-day Free Trial

Initialize An Array With Shorthand Array Initializer

C# also allows for a shorthand of the array initializer. It removes the new and object declaration and only leaves the curly braces. This can save time and typing which should help improve productively. Notice how the compiler can infer the type based on the usage.

//All strings are initialized to book titles
string[] stringArray ={ "The Lion, the Witch and the Wardrobe", "The Diary of a Young Girl", "The Hitchhiker's Guide to the Galaxy" };//Allocates a string array of size 3 with 3 book titles

//Classes are initialized to values
Car[] classArray = { new Car(4, 180, "compact"), new Car(4, 156, "SUV-Crossover"), new Car(4, 140, "MiniVan") };//Allocates a car array of size 3 with 3 car values

//Value types are initialized to 0
double[] doubleArray = { 22.3, 696.89, 943.238200 };//Allocates an double array of size 3
int[] intArray = { 0, 342, 8433 };//Allocates an int array of size 3
float[] floatArray = { 95f, 8207f, 382320.893f };//Allocates an float array of size 3

//Bool will be set to false by default
bool[] boolArray = { false, true, false};//Allocates an bool array of size 3

PrintArrayValues<string>(stringArray, "stringArray");
PrintArrayValues<Car>(classArray, "classArray");
PrintArrayValues<double>(doubleArray, "doubleArray");
PrintArrayValues<int>(intArray, "intArray");
PrintArrayValues<float>(floatArray, "floatArray");
PrintArrayValues<bool>(boolArray, "boolArray");

void PrintArrayValues<T>(T[] array, string ArrayName)
{
    Console.WriteLine($"{ArrayName}:" + string.Join(",", array));
}

class Car
{
    public Car(int wheelCount, int topSpeed, string type)
    {
        WheelCount = wheelCount;
        TopSpeed = topSpeed;
        Type = type;
    }

    public int WheelCount { get; set; }
    public int TopSpeed { get; set; }
    public string Type { get; set; }

    public override string? ToString()
    {
        return $"WheelCount:{WheelCount}, TopSpeed:{TopSpeed}, Type:{Type}".ToString();
    }
}
Code Output
stringArray:The Lion, the Witch and the Wardrobe,The Diary of a Young Girl,The Hitchhiker's Guide to the Galaxy
classArray:WheelCount:4, TopSpeed:180, Type:compact,WheelCount:4, TopSpeed:156, Type:SUV-Crossover,WheelCount:4, TopSpeed:140, Type:MiniVan
doubleArray:22.3,696.89,943.2382
intArray:0,342,8433
floatArray:95,8207,382320.9
boolArray:False,True,False

Initialize An Array With The New Operator

This is first available in C# 9.0. This syntax is just the new keyword. Then the open and closing brackets [] and then the curly braces that have the values. It is a compact syntax that is used across many types in C#. See the example below.

//All strings are initialized to book titles
string[] stringArray = new[] { "Brave New World", "The Picture of Dorian Gray", "The Sun Also Rises" };//Allocates a string array of size 3 with 3 book titles

//Classes are initialized to null
Car[] classArray = new[] { new Car(4, 230, "electric"), new Car(2, 195, "motorcycle"), new Car(4, 134, "hatchback") };//Allocates a car array of size 3 with 3 car values

//Value types are initialized to 0
double[] doubleArray = new[] { 24.6,838.984, 820.281 };//Allocates an double array of size 3
int[] intArray = new[] { 5, 112, 562 };//Allocates an int array of size 3
float[] floatArray = new[] { 238.98f, 2183.32f, 89833.8f };//Allocates an float array of size 3

//Bool will be set to false by default
bool[] boolArray = new[] { true, true, true };//Allocates an bool array of size 3

PrintArrayValues<string>(stringArray, "stringArray");
PrintArrayValues<Car>(classArray, "classArray");
PrintArrayValues<double>(doubleArray, "doubleArray");
PrintArrayValues<int>(intArray, "intArray");
PrintArrayValues<float>(floatArray, "floatArray");
PrintArrayValues<bool>(boolArray, "boolArray");

void PrintArrayValues<T>(T[] array, string ArrayName)
{
    Console.WriteLine($"{ArrayName}:" + string.Join(",", array));
}

class Car
{
    public Car(int wheelCount, int topSpeed, string type)
    {
        WheelCount = wheelCount;
        TopSpeed = topSpeed;
        Type = type;
    }

    public int WheelCount { get; set; }
    public int TopSpeed { get; set; }
    public string Type { get; set; }

    public override string? ToString()
    {
        return $"WheelCount:{WheelCount}, TopSpeed:{TopSpeed}, Type:{Type}".ToString();
    }
}

Know any other ways to initialize an array? Let me know in the comments below.

Get Latest Updates