CodeBlanks Logo Icon CodeBlanks

Declaring arrays

C# course · Beginner · Lesson 53/116

Learn to declare and initialize arrays with int[] and string[].

Declaring arrays

To hold several values of the same type in a single variable you use an array. In C# the array type is marked with square brackets: int[] nums = { 10, 20, 30 };.

The type can vary: string[] for text, double[] for decimals, bool[] for booleans. Once sized, an array keeps its length; it is a fixed-size collection.

Initialization forms

You can initialize an array in two ways. First, a direct value list: int[] nums = { 1, 2, 3 };. Second, give a size with new and assign later: int[] nums = new int[3];.

new int[3] creates a three-element array filled with the default value (0 for int). You can then assign values like nums[0] = 5;. Which form to pick depends on whether you know the values up front.

Exercise Declare an array and print the first element

Declare a nums array with the value { 5, 10, 15 }. Then print nums[0] with Console.WriteLine. The output should be 5.

Show example solution
Write int[] nums = { 5, 10, 15 }; and print it with Console.WriteLine(nums[0]);
Example solution:
using System;

class Program
{
    static void Main()
    {
        int[] nums = { 5, 10, 15 };
        Console.WriteLine(nums[0]);
    }
}

Test yourself

  1. Which is a valid int[] declaration?

    // int array
    • int nums = { 1, 2, 3 };
    • int[] nums = 1, 2, 3;
    • int[] nums = { 1, 2, 3 };
    • int nums[] = { 1, 2, 3 };
    Show answer

    int[] nums = { 1, 2, 3 }; — Correct. int[] nums = { ... }; is the C# array syntax.

  2. Write the square brackets

    int____ nums = { 10, 20, 30 };
    Show answer
    int[] nums = { 10, 20, 30 };
  3. Match each type to its meaning

    int[]
    Number array
    string[]
    Text array
    bool[]
    Boolean array
    double[]
    Decimal array

All lessons in Beginner