C# - Array of Reference Types

In C#, arrays can store elements of reference types, which are objects rather than value types like int or char. Reference types are classes, interfaces, delegates, and other types that are created using the class keyword or are instances of reference types themselves. Here's how you can create and work with arrays of reference types:

1. Creating an Array of Objects (Reference Types):
To create an array of objects (reference types), you can define the array with the appropriate class or interface type. For example, if you have a class called Person, you can create an array to store instances of Person objects.


class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Person[] personsArray = new Person[3];

2. Working with Arrays of Classes:
Once you have created an array of objects, you can access and modify individual elements in the array using index notation.


personsArray[0] = new Person { Name = "Alice", Age = 30 };
personsArray[1] = new Person { Name = "Bob", Age = 25 };
personsArray[2] = new Person { Name = "Charlie", Age = 40 };

3. Handling Null Elements and References:
Arrays of reference types can contain null elements if you don't initialize them explicitly. Null elements mean that the array slots do not point to any object. When accessing elements in the array, you need to handle the possibility of null references to avoid null reference exceptions.


Person[] personsArray = new Person[3];
personsArray[0] = new Person { Name = "Alice", Age = 30 };
// personsArray[1] and personsArray[2] are null

// Accessing elements with null reference handling
if (personsArray[0] != null)
{
    Console.WriteLine(personsArray[0].Name); // Output: Alice
}

// Handling null elements in a loop
foreach (Person person in personsArray)
{
    if (person != null)
    {
        Console.WriteLine(person.Name);
    }
}

4. Array Initialization with Objects:
You can also initialize an array of reference types directly with objects.


Person[] personsArray = new Person[]
{
    new Person { Name = "Alice", Age = 30 },
    new Person { Name = "Bob", Age = 25 },
    new Person { Name = "Charlie", Age = 40 }
};

Arrays of reference types are powerful because they allow you to store and manipulate instances of complex classes. However, you should be mindful of handling null elements to avoid null reference exceptions when working with arrays. Always check for null references before accessing properties or methods of objects in the array.