C# Array of Objects, A Real-World Example

Authors

Arrays are a fundamental concept in computer programming, allowing us to store and manage multiple values in a single data structure.

In C#, arrays can contain not only basic data types such as integers or strings, but also objects.

In this blog post, we'll explore arrays of objects in C# and demonstrate how they can be used in a real-world scenario.

C# Array of Objects

Consider a scenario where we need to keep track of information about a group of employees in a company.

Each employee has several attributes such as name, age, salary, and job title. Instead of creating a separate variable for each employee's information, we can use an array of objects to store all the employee data in a single data structure.

Here's an example of how to define an array of objects in C#:

class Employee
{
    public string Name;
    public int Age;
    public double Salary;
    public string JobTitle;
}

class Program
{
    static void Main(string[] args)
    {
        Employee[] employees = new Employee[3];
        employees[0] = new Employee { Name = "John Doe", Age = 30, Salary = 50000, JobTitle = "Developer" };
        employees[1] = new Employee { Name = "Jane Doe", Age = 35, Salary = 55000, JobTitle = "Manager" };
        employees[2] = new Employee { Name = "Jim Smith", Age = 40, Salary = 60000, JobTitle = "Director" };
    }
}

In this example, we first define an Employee class that has four properties - Name, Age, Salary, and JobTitle.

Then, in the Main method, we create an array of Employee objects and initialize each element with information about a different employee.

With this array of objects, we can easily perform various operations such as printing the information of all employees, finding the employee with the highest salary, or updating an employee's information.

Summary

In conclusion, arrays of objects in C# offer a convenient way to store and manage related data, making it an essential tool for any C# programmer to have in their toolbox.

Whether you're working on a small or large project, arrays of objects can help simplify your code and make it easier to manage your data.

TrackingJoy