Question

C# Array Initialization Syntaxes Explained

csharparrayssyntaxarray-initialization

Question

What array initialization syntaxes are available in C#? Please explain the different valid ways to declare and initialize arrays, including examples of common patterns and when each form is used.

Short Answer

By the end of this page, you will understand the main ways to declare and initialize arrays in C#, how array size and values are assigned, when shorthand syntax works, and which forms are most commonly used in real code.

Concept

In C#, an array is a fixed-size collection of elements of the same type. Array initialization syntax is the set of rules C# gives you for:

  • declaring an array variable
  • creating the array object
  • optionally setting its initial values

This matters because arrays are one of the most common data structures in C#. You use them when you know the number of items ahead of time and want fast indexed access.

A C# array always has:

  • an element type such as int, string, or bool
  • a rank such as one-dimensional ([]) or multidimensional ([,])
  • a fixed length once created

Here is the basic idea:

int[] numbers;

This declares a variable named numbers that can later refer to an array of integers.

To actually create the array:

int[] numbers = new int[3];

This creates space for 3 integers. Because no values were provided, C# fills the array with default values:

  • 0 for int
  • false for bool
  • null for reference types like string

You can also create and fill the array at the same time:

int[] numbers = new int[] { 1, 2, 3 };

Or use the shorter form when the type is already known:

int[] numbers = { 1, 2, 3 };

These syntaxes exist to make code clearer in different situations. Some are more explicit, while others are more concise.

Mental Model

Think of an array like a row of numbered boxes.

  • The type tells you what is allowed in each box.
  • The length tells you how many boxes exist.
  • The initializer tells you what items go into the boxes at the start.

Examples:

  • new int[3] means: “Create 3 boxes for integers.”
  • new int[] { 1, 2, 3 } means: “Create enough integer boxes for these 3 values and place them in order.”
  • int[] numbers = { 1, 2, 3 } means the same thing, just with less typing.

So array initialization is really about choosing between:

  • I know the size
  • I know the values
  • I want both declaration and setup in one place
Take Quiz

Syntax and Examples

Core syntax

1. Declare only

int[] numbers;

This declares a variable, but no array exists yet.

2. Create an array with a fixed size

int[] numbers = new int[5];

This creates an array of length 5 filled with default values:

// numbers = { 0, 0, 0, 0, 0 }

3. Create and initialize with values

int[] numbers = new int[] { 10, 20, 30 };

C# counts the items and creates an array of length 3.

4. Short array initializer

int[] numbers = { 10, 20, 30 };

This is a shorter version of the previous syntax.

5. Separate declaration and later assignment

int[] numbers;
numbers = new int[] { 10, 20, 30 };

This works because the assignment uses new int[] { ... }.

This does not work:

int[] numbers;
// numbers = { 10, 20, 30 }; // Invalid

The short { ... } form is only allowed during declaration.

String array examples

string[] names = new string[2];
string[] cities = new string[] { "Paris", "Tokyo", "Lima" };
string[] colors = { "Red", "Green", "Blue" };

Boolean array example

bool[] flags = new bool[] { true, false, true };

Multidimensional array initialization

int[,] grid = new int[2, 3];

This creates 2 rows and 3 columns.

You can also initialize values:

int[,] grid = new int[,]
{
    { 1, 2, 3 },
    { 4, 5, 6 }
};

Or use the shortened form:

int[,] grid =
{
    { 1, 2, 3 },
    { 4, 5, 6 }
};

Jagged array initialization

A jagged array is an array of arrays.

int[][] jagged = new int[2][];
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5 };

You can also initialize it in one statement:

int[][] jagged = new int[][]
{
    new int[] { 1, 2 },
    new int[] { 3, 4, 5 }
};

Or with less repetition:

int[][] jagged =
{
    new int[] { 1, 2 },
    new int[] { 3, 4, 5 }
};

Step by Step Execution

Consider this example:

int[] scores = { 90, 80, 70 };
Console.WriteLine(scores[1]);

Step by step

  1. int[] scores declares a variable that will store a reference to an integer array.
  2. { 90, 80, 70 } tells C# the starting values.
  3. C# creates an int[] array of length 3.
  4. The values are stored by index:
    • scores[0] = 90
    • scores[1] = 80
    • scores[2] = 70
  5. Console.WriteLine(scores[1]) accesses the second element.
  6. The output is:
80

Another example with default values

string[] words = new string[2];
Console.WriteLine(words[0] == null);

Step by step:

  1. new string[2] creates space for 2 strings.
  2. No values are supplied.
  3. Each element gets the default value for string, which is null.
  4. words[0] == null evaluates to true.

Output:

True

Real World Use Cases

Arrays are useful when the number of items is known and fixed.

Common use cases

  • Storing fixed configuration values

    string[] supportedFileTypes = { ".jpg", ".png", ".gif" };
    
  • Representing game board data

    char[,] board =
    {
        { 'X', 'O', 'X' },
        { 'O', 'X', 'O' },
        { 'X', ' ', 'O' }
    };
    
  • Handling command-line arguments

    static void Main(string[] args)
    {
        Console.WriteLine(args.Length);
    }
    
  • Storing sensor readings or scores

    double[] readings = { 21.5, 21.7, 21.6, 21.8 };
    
  • Working with small lookup tables

    string[] dayNames =
    {
        "Sunday", "Monday", "Tuesday",
        "Wednesday", "Thursday", "Friday", "Saturday"
    };
    

In many apps, arrays are used for low-level storage, fast access, interoperability, and fixed collections.

Take Quiz

Real Codebase Usage

In real C# projects, developers often use array initialization in a few predictable ways.

1. Static known values

private static readonly string[] AllowedRoles = { "Admin", "Editor", "Viewer" };

This is common for constants, allowed values, and small lookup data.

2. Method arguments using arrays

string.Join(", ", new string[] { "A", "B", "C" });

Sometimes the explicit new string[] form is useful when passing an array directly.

3. Validation and membership checks

string[] validStatuses = { "Open", "Closed", "Pending" };

Then the array may be checked using loops or LINQ.

4. Jagged arrays for uneven grouped data

int[][] monthlySales =
{
    new int[] { 10, 20, 30 },
    new int[] { 5, 15 },
    new int[] { 7, 8, 9, 10 }
};

This is useful when inner groups do not all have the same length.

5. Guarding against null before use

if (items == null || items.Length == 0)
{
    return;
}

In real code, arrays are often checked before being processed.

6. Choosing arrays for performance or API compatibility

Arrays are still widely used when:

  • interacting with framework APIs
  • returning fixed groups of values
  • minimizing overhead
  • using low-level or performance-sensitive code

For more flexible collections, developers often use List<T>, but arrays remain very common.

Common Mistakes

1. Confusing declaration with creation

Broken code:

int[] numbers;
Console.WriteLine(numbers.Length);

Problem:

  • numbers is declared but not assigned an array yet.
  • Using it causes a compile-time error because the local variable is not initialized.

Fix:

int[] numbers = new int[3];
Console.WriteLine(numbers.Length);

2. Using the short initializer outside a declaration

Broken code:

int[] numbers;
numbers = { 1, 2, 3 };

Problem:

  • The shorthand { 1, 2, 3 } only works in a declaration.

Fix:

int[] numbers;
numbers = new int[] { 1, 2, 3 };

3. Mixing incompatible element types

Broken code:

int[] numbers = { 1, 2, "3" };

Problem:

  • All elements must match the array element type.

Fix:

int[] numbers = { 1, 2, 3 };

4. Assuming uninitialized elements contain random values

Broken assumption:

int[] numbers = new int[3];
// Expecting garbage values

Reality:

  • C# arrays are automatically filled with default values.
// { 0, 0, 0 }

5. Forgetting that arrays are fixed-size

Broken expectation:

int[] numbers = { 1, 2, 3 };
// numbers.Add(4); // Invalid

Problem:

  • Arrays cannot grow after creation.

Fix:

Use List<int> if you need resizing.

6. Confusing multidimensional and jagged arrays

These are different:

int[,] matrix = new int[2, 2];
int[][] jagged = new int[2][];
  • int[,] is a rectangular grid.
  • int[][] is an array of arrays.

Comparisons

ConceptExampleBest whenNotes
Declare onlyint[] a;You will assign laterNo array exists yet
Fixed size, default valuesint[] a = new int[3];You know the length but not the values yetElements get default values
Explicit initializationint[] a = new int[] { 1, 2, 3 };You want clarity or need assignment after declarationWorks in more places
Short initializationint[] a = { 1, 2, 3 };You are declaring and initializing in one lineMost concise

Arrays vs List

FeatureArrayList<T>
Size after creationFixedGrowable
Index accessYesYes
Initialization shorthandYesCollection initializer syntax
Best forFixed-size dataDynamic collections

Multidimensional vs jagged arrays

TypeExampleShape
Multidimensionalint[,] grid = new int[2, 3];Rectangular
Jaggedint[][] grid = new int[2][];Rows can have different lengths
Take Quiz

Cheat Sheet

// Declare only
int[] a;

// Create fixed size with default values
int[] a = new int[3];

// Create and initialize explicitly
int[] a = new int[] { 1, 2, 3 };

// Create and initialize with shorthand
int[] a = { 1, 2, 3 };

// Assign later
int[] a;
a = new int[] { 1, 2, 3 };

// Multidimensional array
int[,] grid = new int[,]
{
    { 1, 2 },
    { 3, 4 }
};

// Jagged array
int[][] jagged = new int[][]
{
    new int[] { 1, 2 },
    new int[] { 3, 4, 5 }
};

Rules to remember

  • Arrays store elements of one type.
  • Array length is fixed after creation.
  • new T[size] creates default values.
  • { ... } shorthand works only during declaration.
  • Use new T[] { ... } when assigning later.
  • Multidimensional arrays use commas: [,]
  • Jagged arrays use repeated brackets: [][]

FAQ

Can I declare an array without initializing it in C#?

Yes. You can write int[] numbers;, but you cannot use it until it refers to an actual array.

What is the shortest way to initialize an array in C#?

The shortest common form is:

int[] numbers = { 1, 2, 3 };

Why does numbers = { 1, 2, 3 }; not compile?

Because the short initializer syntax only works at the point of declaration. For later assignment, use:

numbers = new int[] { 1, 2, 3 };

What values does a new array contain by default?

Default values based on the element type, such as 0, false, or null.

What is the difference between int[,] and int[][]?

int[,] is a rectangular multidimensional array. int[][] is a jagged array, meaning an array whose elements are arrays.

Should I use an array or a List<T>?

Use an array when the size is fixed. Use List<T> when the number of items may grow or shrink.

Can I initialize arrays of strings, objects, and custom types the same way?

Yes. The syntax is the same; only the element type changes.

Take Quiz

Mini Project

Description

Build a small C# console program that demonstrates the main array initialization syntaxes in one place. This helps reinforce the differences between declaration, fixed-size creation, shorthand initialization, multidimensional arrays, and jagged arrays.

Goal

Create a program that initializes several arrays in different valid ways and prints their contents and lengths.

Requirements

  • Declare an array and assign it later.
  • Create one array using a fixed size and default values.
  • Create one array using the short initializer syntax.
  • Create and print one multidimensional array.
  • Create and print one jagged array.
Take Quiz

Keep learning

Related questions

View more