A2oz

How to Initialize a Class Array in C#?

Published in C++ Programming 2 mins read

You can initialize a class array in C# by using the new keyword followed by the class name and the size of the array in square brackets. Then, you can access each element of the array using its index.

Here's an example:

// Define a class named 'Person'
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// Initialize a class array of size 3
Person[] people = new Person[3];

// Assign values to each element of the array
people[0] = new Person { Name = "John", Age = 30 };
people[1] = new Person { Name = "Jane", Age = 25 };
people[2] = new Person { Name = "Peter", Age = 40 };

Practical Insights:

  • You can also initialize the array with values directly when you declare it:
Person[] people = new Person[] {
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Jane", Age = 25 },
    new Person { Name = "Peter", Age = 40 }
};
  • For more complex scenarios, you can use loops to populate the array with data from other sources.

Solutions:

  • If you need to create an array of a specific size but don't want to initialize it with values immediately, you can use the new keyword with the class name and size, and then populate the array later.

Example:

Person[] people = new Person[10]; // Create an array of size 10

// Populate the array later
people[0] = new Person { Name = "Alice", Age = 28 };
people[1] = new Person { Name = "Bob", Age = 35 };

Conclusion:

Initializing a class array in C# is a straightforward process that involves using the new keyword and specifying the class name and array size. You can then assign values to individual elements of the array using their index.

Related Articles