Start Coding

Topics

C# Arrays

Arrays in C# are powerful data structures that allow you to store multiple elements of the same type in a fixed-size, contiguous block of memory. They provide efficient access to elements using numeric indices.

Declaring and Initializing Arrays

To declare an array in C#, specify the type followed by square brackets and a variable name. Here's a simple example:


int[] numbers;
string[] names;
    

You can initialize arrays in several ways:

1. Using the new keyword


int[] numbers = new int[5]; // Creates an array of 5 integers
    

2. With an initializer list


string[] fruits = new string[] { "apple", "banana", "orange" };
    

3. Implicitly typed arrays


var colors = new[] { "red", "green", "blue" };
    

Accessing Array Elements

Array elements are accessed using zero-based indexing. The first element is at index 0, the second at index 1, and so on.


int[] scores = { 85, 92, 78, 95, 88 };
Console.WriteLine(scores[0]); // Outputs: 85
scores[2] = 80; // Modifies the third element
    

Array Properties and Methods

C# arrays come with useful properties and methods:

  • Length: Returns the total number of elements in the array.
  • Rank: Returns the number of dimensions in the array.
  • Sort(): Sorts the elements in the array.
  • Reverse(): Reverses the order of elements in the array.

Multidimensional Arrays

C# supports multidimensional arrays. These are arrays of arrays, allowing you to create tables or matrices. For more information, check out the guide on C# Multidimensional Arrays.

Jagged Arrays

Jagged arrays are arrays of arrays where each sub-array can have a different length. They offer more flexibility than regular multidimensional arrays. Learn more about them in our C# Jagged Arrays guide.

Array Iteration

You can iterate through arrays using various loop constructs. The foreach loop is particularly useful for arrays:


int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
    Console.WriteLine(num);
}
    

Best Practices

  • Use arrays when you need a fixed-size collection of elements of the same type.
  • Consider using Lists if you need a dynamic-size collection.
  • Always check array bounds to avoid IndexOutOfRangeException.
  • Utilize array methods like Array.Sort() and Array.Find() for common operations.

Conclusion

Arrays are fundamental to C# programming, offering efficient storage and access to collections of data. Understanding how to declare, initialize, and manipulate arrays is crucial for effective C# development. As you progress, explore more advanced concepts like LINQ for powerful array operations.