C# Single-dimensional array
A single-dimensional array in C# is a data structure that stores a fixed-size collection of elements of the same type, organized in a single row. The elements of the array are accessed using a zero-based index, meaning that the index of the first element is 0, the second element is 1, and so on.
Key Features of Single-Dimensional Arrays
- Fixed Size: Once an array is created, its size cannot be changed. The size is specified during the array's creation.
- Homogeneous Elements: All elements of the array must be of the same type.
- Indexed Access: Array elements are accessed using an index, which starts at 0.
- Contiguous Memory: Arrays are stored in contiguous memory locations, which allows for efficient access to elements using their index.
Syntax for Declaring a Single-Dimensional Array
To declare a single-dimensional array in C#, you use the following syntax:
dataType
specifies the type of elements that the array will store.arrayName
is the name of the array.
Creating and Initializing an Array
There are different ways to create and initialize a single-dimensional array in C#.
- Declaring and then initializing the array:
- Declaring, initializing, and assigning values:
- Shorthand initialization:
Accessing and Modifying Array Elements
Array elements are accessed using their index. The index is zero-based, so the first element is at index 0
, the second element is at index 1
, and so on.
Example:
Array Properties and Methods
C# provides several properties and methods for working with arrays:
Length: Returns the total number of elements in the array.
GetValue(int index): Returns the value at the specified index.
SetValue(object value, int index): Sets a value at the specified index.
Sort(): Sorts the array in ascending order.
Reverse(): Reverses the elements of the array.
Iterating Over an Array
You can use a for
loop or a foreach
loop to iterate over the elements of an array.
Example of a for
loop:
Example of a foreach
loop:
Example of Using a Single-Dimensional Array
Summary
- A single-dimensional array is a fixed-size collection of elements, where each element can be accessed using an index.
- Arrays in C# are zero-indexed, meaning the first element is at index
0
. - You can declare, initialize, access, and modify arrays easily using
[]
. - Arrays come with several built-in properties and methods, such as
Length
,Sort()
, andReverse()
.