Absolutely! Arrays in C# are a way to store multiple values of the same type under a single variable name. Think of it like a collection of boxes where you can store different items, but each box can hold only one type of item.
Here's a simple explanation with an example:
Declaration: You declare an array by specifying the type of elements it will contain, followed by square brackets []
and the array name.
Initialization: You can initialize the array with values enclosed in curly braces {}
. These values are separated by commas.
Accessing Elements: You can access individual elements of the array using their index. The index starts from 0
, so the first element is at index 0
, the second at index 1
, and so on.
Here's an example:
Example
using System;
class Program
{
static void Main()
{
// Declaration and Initialization
int[] numbers = { 10, 20, 30, 40, 50 };
// Accessing Elements
Console.WriteLine("First element: " + numbers[0]); // Output: 10
Console.WriteLine("Second element: " + numbers[1]); // Output: 20
Console.WriteLine("Third element: " + numbers[2]); // Output: 30
// Modifying an element
numbers[1] = 25;
Console.WriteLine("Modified second element: " + numbers[1]); // Output: 25
// Length of the array
Console.WriteLine("Length of the array: " + numbers.Length); // Output: 5
}
}
In this example:
numbers
containing integers.{ 10, 20, 30, 40, 50 }
.numbers[0]
for the first element.20
to 25
.Length
property to get the length of the array, which returns 5
.Arrays are useful for storing collections of data that are related in some way, such as a list of temperatures, scores, or names.