0
0
CsharpHow-ToBeginner · 3 min read

How to Declare and Initialize Array in C# - Simple Guide

In C#, you declare an array using the syntax type[] arrayName; and initialize it with values using arrayName = new type[] { values }; or directly with type[] arrayName = { values };. This creates a fixed-size collection of elements of the specified type.
📐

Syntax

To declare an array, specify the type followed by square brackets and the array name. To initialize, use the new keyword with the type and provide values inside curly braces.

  • type[] arrayName; - declares an array variable.
  • arrayName = new type[size]; - creates an array with a fixed size.
  • arrayName = new type[] { values }; - creates and initializes with values.
  • type[] arrayName = { values }; - shorthand declaration and initialization.
csharp
int[] numbers; // Declare an array variable
numbers = new int[3]; // Initialize with size 3

int[] primes = new int[] { 2, 3, 5, 7 }; // Declare and initialize

string[] fruits = { "apple", "banana", "cherry" }; // Shorthand initialization
💻

Example

This example shows how to declare an integer array, initialize it with values, and print each element to the console.

csharp
using System;

class Program
{
    static void Main()
    {
        int[] scores = { 85, 90, 78, 92 };

        Console.WriteLine("Scores:");
        foreach (int score in scores)
        {
            Console.WriteLine(score);
        }
    }
}
Output
Scores: 85 90 78 92
⚠️

Common Pitfalls

Common mistakes when working with arrays in C# include:

  • Forgetting to initialize the array before use, causing a NullReferenceException.
  • Accessing indexes outside the array bounds, which throws an IndexOutOfRangeException.
  • Mixing declaration and initialization syntax incorrectly.

Always ensure the array is initialized before accessing elements and use valid indexes.

csharp
int[] data; // Declared but not initialized
// Console.WriteLine(data[0]); // Wrong: causes error

data = new int[2]; // Correct initialization
Console.WriteLine(data[0]); // Outputs 0 (default int value)
Output
0
📊

Quick Reference

SyntaxDescription
type[] arrayName;Declare an array variable
arrayName = new type[size];Create an array with fixed size
arrayName = new type[] { values };Create and initialize with values
type[] arrayName = { values };Declare and initialize shorthand

Key Takeaways

Declare arrays with type[] arrayName; and initialize before use.
Initialize arrays using new type[size] or with values inside curly braces.
Access array elements only within valid index range to avoid errors.
Use shorthand initialization type[] arrayName = { values }; for simplicity.
Uninitialized arrays cause runtime errors; always initialize before accessing.