C# Aggregation

In C#, Aggregation Represents Has-A Relationship between two objects. A field of the class defines another class to reuse this in the form of association. The class is used as an entity reference. Let's see a simple example of Aggregation where a field address of the class Employee is defined as Address class which contains all of its components. The Address class is instantiated first and then its object is passed in instantiation of Employee class

using System;
public class Address
{
            public string addresslane,city,state;
            public Address(string addresslane,string city,string state)
            {
                        this.addresslane=addresslane;
                        this.city=city;
                        this.state=state;
            }
}
public class Student
{
            public string name;
            int id;
            static int batch=2017;
            static string course="B. Tech.";
            Address address;
            public Student(int id,string name,Address address)
            {
                        this.id=id;
                        this.name=name;
                        this.address=address;
            }
            public void display()
            {
            Console.WriteLine(id+" "+name+" "+address.addresslane+" "+address.city+" "+address.state+" "+course+" "+batch);
            }
}
public class AggregationExample
{
            public static void Main (string[] args)
            {
            Address a=new Address("s-15 sector 16","noida","UP");
            Student s=new Student(101,"Ayush",a);
            s.display();
}
}
Output
101 Ayush s-15 sector 16 noida UP B. Tech. 2017



ADVERTISEMENT
ADVERTISEMENT