Declaring Arrays
Part of the Fundamentals section of Coddy's C# journey — lesson 55 of 69.
An array is a collection of items, and it can contain values of different types, such as numbers, strings, or even other arrays. Arrays are created using square brackets [], and the items inside the array are separated with commas.
Here is an example of how to create an array:
int[] numbers = {1, 2, 3, 4, 5};To check the length of the array, we can use the .Length field:
int length = numbers.Length;The variable length will hold 5 because there are 5 elements in the array.
Another way to create an array using the new keyword followed by the array type and size:
int[] numbers = new int[5];Creates an array of 5 integers, all initialized to 0
Challenge
EasyCreate an array called shoppingList that contains the following items: bread, eggs, milk, and butter.
Cheat sheet
Arrays are collections of items created using square brackets [] with items separated by commas:
int[] numbers = {1, 2, 3, 4, 5};Check array length using the .Length field:
int length = numbers.Length;Create arrays with the new keyword specifying type and size:
int[] numbers = new int[5]; // Creates array of 5 integers, all initialized to 0Try it yourself
public class Program {
public static void Main(string[] args) {
// Create the shoppingList array here
// Don't change the code below
System.Console.WriteLine("Shopping List:");
for (int i = 0; i < shoppingList.Length; i++) {
System.Console.WriteLine(shoppingList[i]);
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 311Arrays Basics
Declaring ArraysAccessing ElementsModifying ArraysArray MethodsRecap - Product ArrayEdit Recap - Reversed Array