C# Arrays Introduction
An array in C# is a collection of elements of the same type stored in contiguous memory locations. Arrays are useful for storing multiple values in a single variable, making it easier to manage and manipulate data sets.
Key Topics
1. Declaring Arrays
You can declare an array by specifying the type of its elements, followed by square brackets []
. For example:
int[] numbers;
2. Initializing Arrays
Arrays can be initialized at the time of declaration or later in the code.
Example: Declaring and Initializing an Array
// Declaration and initialization
int[] numbers = new int[5];
// Assigning values
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Alternatively, declare and initialize in one line
int[] numbers2 = { 10, 20, 30, 40, 50 };
Code Explanation: The array numbers
is declared with a size of 5 and then each element is assigned a value individually. The array numbers2
is both declared and initialized with values in a single line.
3. Array Syntax
The general syntax for declaring and initializing arrays:
type[] arrayName = new type[size]; // Declaration with size
// or
type[] arrayName = { value1, value2, value3 }; // Declaration with initialization
Key Takeaways
- Arrays store multiple values of the same type in a single variable.
- They are declared using square brackets
[]
after the type. - Arrays can be initialized during declaration or assigned values later.
- Understanding array syntax is fundamental to using arrays effectively.