C# Aggregation (HAS-A Relationship)

In C#, aggregation is a type of relationship between classes where one class has a reference to another class, often referred to as a “HAS-A” relationship. Aggregation is a form of association that represents a whole-part or container-contained relationship.

To establish an aggregation relationship between classes in C#, you can use a member variable or property of one class to hold an instance of another class. Here’s an example to illustrate how aggregation works:

class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

class Person
{
    public string Name { get; set; }
    public Address Residence { get; set; } // Aggregation relationship

    public Person(string name, Address residence)
    {
        Name = name;
        Residence = residence;
    }
}

class Program
{
    static void Main()
    {
        Address address = new Address
        {
            Street = "123 Main St",
            City = "Exampleville",
            Country = "Exampleland"
        };

        Person person = new Person("John Doe", address);

        Console.WriteLine($"Name: {person.Name}");
        Console.WriteLine($"Residence: {person.Residence.Street}, {person.Residence.City}, {person.Residence.Country}");
    }
}

In the example above, the Person class has an aggregation relationship with the Address class. The Person class has a property called Residence of type Address, which represents the address of the person’s residence. The Person class “has” an Address object.

By using aggregation, you can encapsulate related objects within a class and access them through their associated class instances. In this case, a Person can have an Address object as their residence, and you can access the person’s residence details through the Residence property.

Aggregation allows for creating more complex class structures and is useful when you want to represent relationships where one class contains or has access to another class.