Start learning free

LESSON 87 OF 347 · ARRAYS I

Static Arrays in C#: Creating and Initializing

Lesson Read the full explanation

When we're dealing with large amounts of data, we want to make sure we can organize and manage it properly.

In C#, we use arrays to store several pieces of data in one place. The items in an array must be of the same data type.

A static array or fixed array is an array for which the size / length is determined when the array is created and/or allocated.


Creation:

We create a static array by using the keyword new, then writing the data type of the elements and the array's length inside []:

string[] arrayOfStrings = new string[3];

In this program we created an array named arrayOfStrings that consists of 3 string items.

These 3 items are null (no value given yet) initially.


Creation & Initialization:

There is a way to initialize an array at creation by using the = operator with an opening bracket, end it with a closing bracket, and put a comma between each entry, like this:

string[] arrayOfStrings = {"AlgoCademy", "coding", "static arrays"};

We created an array named arrayOfStrings which consits of 3 String items: "peanut butter", "jelly" and "bread".


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    C# · ARRAYS I

    Static Arrays in C#, explained

    What an array is

    An array stores several values of the same type in one variable. Instead of declaring age1, age2, age3 and so on, you declare one array and refer to each value by its position.

    A static (or fixed-size) array has a length that is decided when the array is created. It never grows or shrinks afterwards. If you need a collection that changes size, C# has List<T>, which the next lessons cover.

    Creating an array with new

    Write the element type followed by [] for the variable's type, then new, the element type again, and the length in brackets:

    string[] arrayOfStrings = new string[3];
    int[] numbers = new int[20];
    

    The first line creates room for 3 strings, the second for 20 integers. The length is part of the object, not of the variable's type: int[] means "an array of ints" of any length.

    Default values

    A new array is never uninitialized. Every slot starts with the default value of its type:

    Element typeDefault value
    int, double and other numbers0
    boolfalse
    string and other reference typesnull

    So new int[20] gives you twenty zeros, while new string[3] gives three null references. Reading arrayOfStrings[0] returns null until you assign something. Calling a method on that null, such as arrayOfStrings[0].Length, throws a NullReferenceException.

    Creating and filling in one step

    If you already know the values, list them in braces. The compiler counts them, so you don't write the length:

    string[] fruits = {"mango", "kiwi", "grapefruit"};
    Console.WriteLine(fruits.Length);  // 3
    

    The same array can also be written with an explicit new, and both forms mean the same thing:

    string[] a = new string[] {"mango", "kiwi", "grapefruit"};
    string[] b = new[] {"mango", "kiwi", "grapefruit"};
    

    Recent C# versions also accept collection expressions, string[] c = ["mango", "kiwi", "grapefruit"];. Whichever form you choose, the values in the braces must be of the array's element type. An array of ints can't hold a string.

    Arrays are reference types

    An array variable doesn't contain the elements themselves. It holds a reference to an array object created by new. Two consequences are worth knowing early. First, a variable can be declared without an array and hold null until you create one. Second, assigning one array variable to another makes both names refer to the same array, not a copy.

    Arrays are also not limited to ints and strings. Any type can be an element type, for example double[], bool[] or char[], and a new double[2] holds two zeros.

    The exercise, step by step

    1. An integer array of size 20. Write int[] numbers = new int[20];. The variable name is numbers, the element type is int, and the length 20 goes inside the brackets after new int. All twenty elements start at 0.
    2. A string array with three fruits. Write string[] fruits = {"mango", "kiwi", "grapefruit"};. No length is needed because the braces list exactly three values.

    The complete solution is two lines:

    int[] numbers = new int[20];
    string[] fruits = {"mango", "kiwi", "grapefruit"};
    

    Common mistakes

    • Using parentheses instead of brackets. new int(20) is not an array. The length goes in square brackets: new int[20].
    • Putting the length in the variable's type. int[20] numbers doesn't compile. The type is just int[].
    • Giving a length and a different number of values. new int[3] {1, 2} is an error, because the length and the initializer disagree.
    • Using the brace shortcut after the declaration. fruits = {"a", "b"}; on a variable that already exists doesn't compile. The shortcut only works in a declaration. Later, write fruits = new string[] {"a", "b"};.
    • Lowercase type names. C# is case-sensitive. The keyword string is lowercase, and String is also valid, but new Int[20] is not.

    Things to try

    Experiment in the editor to see the defaults for yourself. Print numbers.Length to confirm the length is 20, and print numbers[5] to see 0. Create new string[2], assign "hi" to its first slot, and check that the second slot still equals null. Seeing these defaults first-hand makes the difference between value types such as int and reference types such as string easier to remember.

    Key takeaways

    • An array holds values of one type, and its length is fixed when it is created.
    • new int[20] creates 20 zeros; new string[3] creates 3 null references.
    • Braces after the declaration, as in {"mango", "kiwi", "grapefruit"}, set the values and the length together.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free