An array in C# is a collection of variables of the same type stored in contiguous memory locations. Arrays are useful for storing multiple values in a single variable.
int[] numbers = new int[5];
— Declares an integer array with 5 elements (default values are 0).int[] numbers = {1, 2, 3, 4, 5};
— Declares and initializes an array with values.string[] fruits = new string[] {"Apple", "Banana", "Mango"};
— String array initialization.You access array elements by their index (starting from 0):
int[] numbers = {10, 20, 30, 40, 50};
Console.WriteLine(numbers[0]); // Output: 10
numbers[2] = 100; // Changing the third element
Console.WriteLine(numbers[2]); // Output: 100
Commonly, we use a for
loop or foreach
loop to iterate over all elements:
string[] fruits = { "Apple", "Banana", "Mango" };
// Using for loop
for (int i = 0; i < fruits.Length; i++)
{
Console.WriteLine(fruits[i]);
}
// Using foreach loop
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
0
.Length
property gives the size of the array.Summary
for
or foreach
.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!