Understanding Arrays in C#

Understanding Arrays in C#

In today's lesson, we'll explore arrays in C#, a versatile and fundamental data structure. An array is an ordered collection of elements that can be of mixed data types. Arrays in C# are mutable, meaning their elements can be changed after creation. However, arrays can be made immutable using certain techniques if needed.

The beauty of arrays lies in their simplicity and efficiency; they allow for easy storage, access, and manipulation of data. By the end of this lesson, you'll be able to create, manipulate, and understand the unique applications of arrays in C#.

Creating Arrays

Arrays are a fundamental part of C# programming, allowing you to define collections of elements of the same type. There are two primary ways to create arrays in C#: using array literals and using constructors with the new keyword.

  1. Array Literals: An array can be declared and initialized with specific values directly using an array literal. This involves enclosing the elements within curly braces {} without using the new keyword.

  2. Using Constructors: Arrays can also be created using the new keyword followed by the type, square brackets [], and the elements enclosed in curly brackets {}. This approach explicitly specifies the array's type and initializes it with values.

It is considered best practice to declare arrays with readonly in C# when the reference to the array itself should not change, but the contents can.

In the next C# example, we illustrate array creation using both array literals and constructors:

C#
using System;

class ArrayExample
{
    public (string[] arrayLiteral, string[] fromConstructor) CreateArrays()
    {
        string[] arrayLiteral = { "apple", "banana", "cherry" }; // Using array literals
        string[] fromConstructor = new string[] { "apple", "banana", "cherry" }; // Using constructor
        return (arrayLiteral, fromConstructor);
    }
}

class Program
{
    static void Main()
    {
        var arrayExample = new ArrayExample();
        var arrays = arrayExample.CreateArrays();
        Console.WriteLine(string.Join(", ", arrays.arrayLiteral)); // Output: apple, banana, cherry
        Console.WriteLine(string.Join(", ", arrays.fromConstructor)); // Output: apple, banana, cherry
    }
}

This example demonstrates how to create arrays using both the array literal method and the constructor method, providing the same resulting arrays in both cases.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal