Array of objects C# example – An array of user defined class objects can also be created the same way as we create array of built-in type.
For example, here is an array for 5 int type.
int [] numbers = new int[5];
Similarly, an Array of 5 objects of the class Car can be created as below.
Car[] obj = new Car[5];
In an array of objects, all the objects will be of same class.
We have created array for 5 Car objects in which we can store 5 objects of Car class.
Now for each 0 to 4 slot, we can create Car object as below.
obj[0] = new Car();
obj[1] = new Car();
obj[2] = new Car();
obj[3] = new Car();
obj[4] = new Car();
Array of objects C# example – Source code
This program creates an array of 5 objects of class Car. Set the name of each car. Using for loop, it will retrieve each array elements and display the names of the
cars on console.
/*
* Array of objects in C# example program
*/
class Car
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
/*
* Test array of objects
*/
class Program
{
static void Main(string[] args)
{
// Create an array of 5 student objects.
Car[] obj = new Car[5];
// Create first car object
obj[0] = new Car();
// Set car names
obj[0].setName("Maruti");
obj[1] = new Car();
obj[1].setName("Honda");
obj[2] = new Car();
obj[2].setName("Ford");
obj[3] = new Car();
obj[3].setName("Hundai");
obj[4] = new Car();
obj[4].setName("Nissan");
// Display all cars
for (int i = 0; i < 5; ++i)
{
Console.WriteLine("Car : " + obj[i].getName());
}
}
}
Output
Car : Maruti
Car : Honda
Car : Ford
Car : Hundai
Car : Nissan