HI WELCOME TO SIRIS

C# Aggregation (HAS-A Relationship)

Leave a Comment
In C#, aggregation is a process in which one class defines another class as any entity reference. It is another way to reuse the class. It is a form of association that represents HAS-A relationship.

C# Aggregation Example

Let's see an example of aggregation where Employee class has the reference of Address class as data member. In such way, it can reuse the members of Address class.
  1. using System;  
  2. public class Address  
  3. {  
  4.     public string addressLine, city, state;  
  5.     public Address(string addressLine, string city, string state)  
  6.     {  
  7.         this.addressLine = addressLine;  
  8.         this.city = city;  
  9.         this.state = state;  
  10.     }  
  11. }  
  12.    public class Employee  
  13.     {  
  14.        public int id;  
  15.        public string name;  
  16.        public Address address;//Employee HAS-A Address  
  17.        public Employee(int id, string name, Address address)  
  18.        {  
  19.            this.id = id;  
  20.            this.name = name;  
  21.            this.address = address;  
  22.        }  
  23.        public void display()  
  24.        {  
  25.            Console.WriteLine(id + " " + name + " " +   
  26.              address.addressLine + " " + address.city + " " + address.state);  
  27.        }  
  28.    }  
  29.    public class TestAggregation  
  30.    {  
  31.         public static void Main(string[] args)  
  32.         {  
  33.             Address a1=new Address("G-13, Sec-3","Noida","UP");  
  34.             Employee e1 = new Employee(1,"Sonoo",a1);  
  35.             e1.display();  
  36.         }  
  37.     }  
Output:
1 Sonoo G-13 Sec-3 Noida UP

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.