Declaring arrays
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
-
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.
-
Write the square brackets
int____ nums = { 10, 20, 30 };Show answer
int[] nums = { 10, 20, 30 }; -
Match each type to its meaning
- int[]
- Number array
- string[]
- Text array
- bool[]
- Boolean array
- double[]
- Decimal array