Aggregation in C#

 

Aggregation, otherwise known as a “has-a” or “part-of” relationship, gathers one or more objects from various classes and places them inside another class. Aggregation, therefore, reuses classes by assembling objects of existing classes to define, at least in part, the data members and methods of a new class. In order to define the class FirstClass, a single object of the SecondClass class is placed inside FirstClass along with two additional data members, min and max. Also included are methods to return the minimum and maximum values, GetMax and GetMin, as well as a method InitRange to set the bounds. By default, the count for an object of FirstClass is initialized to min upon creation.

 

public class SecondClass

{

        public string GetData()

        {

            return "this is SecondClass Class";

        }

    }

 

    public class FirstClass

    {

        public FirstClass(int min, int max)

        {

            this.c = new SecondClass(); // Creates a private SecondClass c

            InitRange(min, max);

        }

        private void InitRange(int min, int max)

        {

            this.min = min;

            this.max = max;

        }

        public string GetData() { return c.GetData(); }// Reuses object c

       

        public int GetMin() { return min; }

        public int GetMax() { return max; }

        private SecondClass c; // Reuses object SecondClass c by aggregation

        private int min;

        private int max;

}

 

Although aggregation does work to define FirstClass, it is not a particularly elegant solution. The methods GetCount and SetCount of FirstClass are reimplemented using the existing methods of SecondClass. In this case, where behavior is common, inheritance provides a better mechanism than aggregation for class reuse. In Section 3.3.3, the opposite is demonstrated.