Arrays for Classes
You can use arrays of objects. Creating arrays of objects is pretty much the same as when creating arrays for primitive data types such as int. For example, we can create an array of the Person class.
using System;
namespace ArrayOfObjectsDemo
{
public class Person
{
public string Name { get; set; }
public Person(string name)
{
Name = name;
}
}
public class Program
{
public static void Main()
{
Person[] people = new Person[3];
people[0] = new Person("Johnny");
people[1] = new Person("Mike");
people[2] = new Person("Sonny");
foreach (Person person in people)
{
Console.WriteLine(person.Name);
}
}
}
}
Example 1 – Creating an Array of Objects
Johnny Mike Sonny
We created a class that has one property. We then declared an array of that class and initialized them with new instances. We displayed the value for the property of each instance using a foreach loop.
You can use the other techniques you have learned when creating arrays. For example, you can recreate the program in Example 1 to use the other version of initializing and declaring arrays.
Person[] people = new Person[]
{
new Person("Johnny"),
new Person("Mike"),
new Person("Sonny")
};
Here, the people array was declared with 3 elements because the compiler automatically counts the number of instances you provided. You can use these techniques for creating multidimensional and jagged arrays involving classes.