- Author

- Name
- Nelson Silva
- Social
Introduction
The ability to group and manipulate sets of items efficiently is a fundamental need in programming. In C#, arrays are the foundational structure for this purpose, serving as pillars in the construction of robust and dynamic applications.
What is an Array?
At the heart of programming, arrays are structures that store multiple values under a single name. Think of them as shoeboxes on a shelf: each box can hold a shoe, and you can identify each box (and the shoe inside it) by its position on the shelf.
Array Properties:
- Fixed Size: Once defined, the size of an array cannot be changed.
- Indexed Access: Each element in the array has an index, usually starting from zero, allowing direct access to any element.
- Homogeneous Type: All items within an array must be of the same type.
using System;
namespace Base {
class Arrays {
public void Run() {
// Declaring and initializing a string array
string[] colors = new string[] {
"Blue",
"Green",
"Yellow",
"Red",
"Orange"
};
Console.WriteLine($"Number of colors: {colors.Length}"); // Number of colors: 5
Console.WriteLine($"First color: {colors[0]}"); // First color: Blue
Console.WriteLine($"Last color: {colors[colors.Length - 1]}"); // Last color: Orange
}
}
}
Basic Array Operations
Value Assignment
You can assign values to an array at the time of declaration, as shown above, or at a later time using the index.
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
Accessing Values
The values stored in an array can be accessed directly by index:
Console.WriteLine(numbers[0]); // 10
Common Array Operations
- Length: Returns the number of elements in the array.
- Clone: Creates a shallow copy of the Array.
- IndexOf: Returns the index of the first occurrence of a value.
- LastIndexOf: Returns the index of the last occurrence of a value.
- Contains: Checks whether the Array contains a specific element.
Conclusion
Arrays play a fundamental role in C# programming. They are an indispensable tool for developers, enabling efficient manipulation of data sets. Mastering the use of arrays is therefore crucial for anyone who wants to deepen their knowledge of C#.