C# Aggregation

In C#, aggregation refers to a connection where a class retains a reference to another class, enabling the utilization of one class within another. This type of relationship signifies a "Has-A" association between distinct classes, with each class capable of independent existence while one class includes a reference to the other. Aggregation supports the enhancement of code reusability, simplicity, and maintainability in software development.

Syntax:

It has the following syntax.

Example

class ClassA

{

    // fields, methods, etc.

}

class ClassB

{

    // Aggregation: ClassB has a reference to ClassA

    ClassA obj;

    // Constructor to accept an existing ClassA object

    public ClassB(ClassA obj)

    {

        this.obj = obj;

    }

    // methods, etc.

}

In this syntax,

ClassA stands independently as a class with its unique set of fields and methods, while ClassB includes an object reference of ClassA to demonstrate aggregation.

C# Aggregation Example

Let's consider a scenario to demonstrate aggregation in C#.

Example

Example

using System;

// create a class 

class information

{

    public string City;

    public string Country;

    public long Contact;

    // declaration constructor 

    public information(string city, string country, long contact)

    {

        City = city;

        Country = country;

        Contact = contact;

    }

}

// declare a student class

class Stu

{

    public int Id;

    public string Name;

    public information Ddr;  // Aggregation

    public Stu(int id, string name, information ddr)

    {

        Id = id;

        Name = name;

        Ddr = ddr; 

    }

    public void Display()

    {

        Console.WriteLine("ID is " + Id + ", Name is " + Name);

        Console.WriteLine("City is " + Ddr.City + ", State is " + Ddr.Country + ", Contact is " + Ddr.Contact);

    }

}

class Program

{

    static void Main()

    {

        // Use Details 

        information d1 = new information("New York", "USA", 356545161);

        Stu s1 = new Stu(1, "John", d1);

        s1.Display();

    }

}

Output:

Output

ID is 1, Name is John

City is New York, State is USA, Contact is 356545161

Explanation:

In the C# application, we declare two classes named Pupil and DataHolder. The data holder class retains various particulars like location, region, and phone number. The pupil class holds fundamental information, identification, and full name, and additionally, it contains a connection to a data holder entity. Within the main function, an instance of the data holder is instantiated and transferred to a pupil instance to display the merged information.

Composition in C#

In C# programming, composition is a unique form of aggregation that signifies a part-of connection. When the parent object is removed in a composition, the child object is likewise eliminated as it relies on the parent and cannot exist on its own.

For Example: A House has Rooms. If the house is destroyed, the rooms also disappear.

Syntax:

It has the following syntax.

Example

class Part

{

    // method, member;

}

class Whole

{	

    privatePart part; // Composition

    public Whole()

    {

        part = new Part(); // Child created inside parent

    }

}

In this syntax,

The Part class functions as an independent entity (child) that is generated and managed by the Whole class (parent). The parent class instantiates the part class internally, resulting in the part's lifecycle being entirely reliant on the parent. In case the parent is removed, the child is likewise eliminated.

C# Composition Example:

Let's consider a scenario to demonstrate the concept of composition in C# using a Home and Room as an example.

Example

Example

using System;

// Declare a class Room

class Room

{

    public string Name { get; set; }   // Property should match the constructor

    public Room(string n)

    {

        Name = n;      // Use Name with uppercase to match property

    }

    public void ShowRoom()

    {

        Console.WriteLine("The room is " + Name);

    }

}

// Declare a class House

class home

{

    private Room room; // Composition: House contains a Room

    public home(string roomName)

    {

        room = new Room(roomName); // Child object created in constructor

    }

    public void Show()

    {

        room.ShowRoom();  // Call the Room's method

        Console.WriteLine("This room belongs to the house.");

    }

}

// Main Program

class Program

{

    static void Main()

    {

        home myhome = new home("Living Room");

        myhome.Show();

        // Room cannot exist without the home

    }

}

Output:

Output

The room is the Living Room

This room is part of the house.

Explanation:

In this instance, we define a pair of classes titled Chamber and Dwelling. The chamber class holds the property called title and additionally features the DisplayChamber function to exhibit the title of the chamber. Following this, the dwelling class illustrates composition by generating its individual Chamber object and invoking the DisplayDwelling function. Within the primary method, we instantiate a Dwelling class object and invoke the DisplayDwelling function to present the expected result.

Difference between Aggregation and Composition

In C#, the concepts of aggregation and composition exhibit variations in the following manners.

Aggregation Composition
It is a special type of association. It is a special type of aggregation.
Every object has its own life cycle. The child object does not have its own life cycle. It mainly depends on its parent's life cycle.
It is a weak association. It is a strong association.
Aggregation means one object just uses another class. It means one class is fully made up of another class. The composition indicates that one object is contained in another class.
The parent class is not responsible to create or destroy the child class. The parent class is responsible to create or remove the child class.

Aggregation Function in LINQ

In C#, within LINQ, aggregation functions refer to functions that merge values from multiple rows into a single output value. Therefore, it can be stated that the C# aggregate function consistently generates a solitary value.

An actual instance of an aggregation function is determining the overall company revenue generated from sales.

Below are the methods commonly employed to execute the aggregation process.

Methods Description
Aggregate It carries out a custom aggregation operation on the elements of a collection.
Count It counts the elements in the collection.
Average It determines the average of the collection of values.
LargeCount It counts the elements in the large collection
Max It calculates the maximum value of the collection.
Min It calculates the minimum value of the collection.
Sum It determines the sum of the values of the collection.

C# LINQ Aggregation Example

Let's consider an example to compute the total of the numerical values.

Example

Example

using System;

using System.Linq;

public class C# Tutorial {

    // Main Method

    static public void Main()

    {

        int[] seq = {200, 400, 500, 600, 100, 

                          8, 99, 9, 5, 6};

        Console.WriteLine("The total of all the number is: ");

        // Using Sum() aggregation function

        int res = seq.Sum();

        Console.WriteLine(res);

    }

}

Output:

Output

The total of all the numbers is:

1927

Explanation:

In this instance, we utilize the Sum aggregation function from the System.Linq namespace. Initially, we set up the integer array and start the number sequence. Within the main function, it computes the overall sum of the elements within the array by employing the Sum technique. Lastly, we employ the Console.WriteLine method to display the result.

Advantages of Using C# Aggregation

Several advantages of C# aggregation are as follows:

  • It represents a unidirectional HAS-A relationship between the objects of two classes.
  • It also helps to enhance code reusability.
  • It improves the code's readability and make it understandable to represent the relationship.
  • It consists of more restrictions as compared to the association.
  • Conclusion

In summary, the aggregation in C# refers to one class holding a reference to another class, enhancing code organization for increased flexibility, scalability, and component reuse. This method proves beneficial in managing large-scale applications. To enhance maintainability and support future updates, it is essential for components to interact without creating rigid dependencies.

C# Aggregation FAQs

1) What is Aggregation in C#?

In C#, aggregation refers to one class maintaining a reference to another class, offering a means of class reusability. This type of association signifies a "Has-A" relationship between classes, allowing both classes to function independently while one class includes a reference to the other.

2) Is Aggregation the same as inheritance in C#?

Aggregation differs from inheritance. Aggregation signifies a "has-a" connection between distinct classes, allowing both classes to operate autonomously while one class includes a reference to the other.

3) Does Aggregation support polymorphism?

Yes, the combination of objects supports the concept of polymorphism. Polymorphism can be attained by storing instances of derived classes when the combined object is of an interface or base class type.

Is it possible to achieve Aggregation without utilizing a constructor method?

Yes, in C# it is possible to perform aggregation without the necessity of a constructor. It is feasible to pass an already existing object to another class through a constructor. However, after the object has been instantiated, the reference can alternatively be set using properties or setter methods.

5) What are some practical instances of Aggregation in C#?

The real-life examples of aggregation are:

  • The School has teachers
  • The Library has teachers
  • The Team has players

Input Required

This code uses input(). Please provide values below: