Arrays and Collections
Arrays and collections are used in C# to store and manipulate data. They provide a way to organize and access multiple elements of the same type.
Arrays
An array is a fixed-size collection of elements of the same type. You can think of it as a container that holds multiple values. Each value in an array is called an element, and is accessed using its index.
Here's an example of an array in C#:
1int[] numbers = { 1, 2, 3, 4, 5 };
In this example, numbers
is an array that holds 5 integers. The elements of the array can be accessed using their index. For example, numbers[0]
represents the first element of the array.
You can iterate through an array using a for loop, like this:
1for (int i = 0; i < numbers.Length; i++)
2{
3 Console.WriteLine(numbers[i]);
4}
This will print each element of the array.
Collections
Collections are similar to arrays, but they have dynamic size and can hold elements of different types. The .NET framework provides various collection classes that you can use in your C# programs.
One commonly used collection class is the List<T>
class, which provides a way to store and manipulate a collection of objects of type T
.
Here's an example of using a List<int>
to store a collection of integers:
1List<int> numbersList = new List<int>();
2numbersList.Add(1);
3numbersList.Add(2);
4numbersList.Add(3);
5
6foreach (int number in numbersList)
7{
8 Console.WriteLine(number);
9}
In this example, numbersList
is a List<int>
that holds 3 integers. The Add()
method is used to add elements to the list, and the foreach
loop is used to iterate through the elements and print them.
Arrays and collections are powerful tools in C# that allow you to store and manipulate data in your programs.
xxxxxxxxxx
// Example of an array
int[] numbers = { 1, 2, 3, 4, 5 };
// Iterate through the array using a for loop
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}