find and solve || findandsolve.com
Please wait.....

C# Aggregation

Aggregation in C# is a process in which one class defines another class as an entity reference. It is another way to reuse the class.

C# Aggregation Example

We are going to see an example of aggregation where EmployeeInfo class has the reference of Address class as a data member. In such a way, it can reuse the members of the Address class.

using System;  

public class Address
{
    public string address1, address2, city;
    public Address(string address1, string address2, string city)
    {
        this.address1 = address1;
        this.city = city;
        this.address2 = address2;
    }
}
   public class EmployeeInfo
    {
       public int Id;
       public string Name;
       public Address address;//EmployeeInfo HAS-A Address
       public EmployeeInfo(int id, string name, Address address)
       {
           this.Id = id;
           this.Name = name;
           this.address = address;
       }
       public void display()
       {
             Console.WriteLine(Id + " " + Name + " " +
             address.address1 + " " + address.city + " " + address.address2);
       }
   }
   public class AggregationExample
   {
        public static void Main(string[] args)
        {
            Address objAddress =new Address("Buddhangar", "Sankhamul","KTM");
            EmployeeInfo objEmployeeInfo = new EmployeeInfo(1001,"Buddhangar",objAddress);
            objEmployeeInfo.display();
        }
    }  

Output

1001 Buddhangar Buddhangar KTM Sankhamul