Lesson: C# Arrays

What is an Array in C#?

An array is a data structure that can hold multiple values of the same type in a single variable. Arrays are used to store a collection of data, and they are particularly useful when you need to work with a large set of data that can be accessed by index.

Declaring and Initializing an Array

You can declare an array in C# using the following syntax:

int[] numbers = new int[5];

This creates an integer array that can hold 5 elements. The index of an array starts at 0, so this array will have indices 0, 1, 2, 3, and 4.

Accessing Elements of an Array

You can access elements in an array by their index:

numbers[0] = 10; // Assigns 10 to the first element

The above code assigns the value 10 to the first element of the `numbers` array.

Array Example: Manipulating Array Elements

Use the input fields below to enter values into an array and see the result:






Array Contents:

[]

Quiz: Test Your Knowledge on C# Arrays

1. What is the index of the first element in an array?




2. How do you access the third element of an array called `arr`?




3. What does the following code do?

int[] numbers = { 1, 2, 3, 4, 5 }; Console.WriteLine(numbers[2]);



4. How would you declare an array of strings in C#?




5. Which of these methods will you use to find the length of an array?