1. OnlineBuff

Understand Association, Composition, Aggregation and Inheritance in C#

Overview: -

In this article we will try to understand how to implement relationships in c-sharp using object oriented principles like inheritance, association, aggregation and composition with a simple example and explanation using c-sharp.

To make you understand about inheritance, association, aggregation and composition let me take up a real world scenario. 

Extracting Sales Firm working scenario

1. SalesManager is an employee of PQRCompany

2. SalesTeam are employees of PQRCompany.

3. SalesManager has an employeecard to enter into PQRCompany.

4. SalesManager has got SalesTeam to work under him.

5. SalesManager has got responsibility to sell the products and to achieve the monthly target.

All these relationship is based on "is a" relationship, "has-a" relationship and "part-of" relationship. So let me explain you this one by one.

 

Inheritance based on IS-A Relationship

Definition 

Inheritance in C# is a parent-child relationship where we create a new class by using existing class code (i.e. reusing methods, properties and other variables). Inheritance allows us to reuse of the code again again means parent class can be implemented to any number of child classes. Inheritance uses special character called ":" colon to make a relationship.


Now let's extract above example (1, 2)


1. SalesManager is an employee of PQRCompany.2. SalesTeam are employees of PQRCompany.


In this above example our parent is a PQRCompany. SalesManager is an employee works in PQRCompany and SalesTeam are working in the PQRCompany.So there is a parent-child relationship between PQRCompany-SalesManager and PQRCompany-SalesTeam, because SalesManager and SalesTeam work under same company. Now let put this in the coding style.

 

public class PQRCompany{
//more code 
}

public class SalesManager : PQRCompany {
//more code 
}

public class SalesTeam : PQRCompany {
//more code 
}

Instead of using a company name as a parent you can also use "employee" as a parent class because SalesManager and SalesTeam are both employees only.But it is optional it can change according to scenario if you need you can keep "Company" as a parent or "Employee" as a parent. So this is how we need to implement parent-child relationship in our code according to the scenario. 

Click here to know more on:  Implementing inheritance in C#.

 

Association is based on HAS-A Relationship

 

What is an Association in C#

Association is based on "has-a" relationship principle. Let me explain you the definition using a simple example. Consider we have two different classes Class1 and a Class2  when both of these entities share each other’s object for some work and at the same time they can exists without each others dependancy (having their own life time)  and there should be no single owner both have to be an independent from each other then type of relationship is known as "has-a" relationship i.e. Association.

Now let's extract example no (3).

3. SalesManager has an employeecard to enter in PQRCompany.

In this example we will extract association principle. SalesManager uses an employeecard to enter in the company. Here we need to create two classes "SalesManager" and "EmployeeCard" because SalesManager is an employee of a company and company uses an employeecard to authorize their employees so both have to a different entities and at a same we should violate single responsibility principle means we can't give employeecard class job to salesmanager class. 

Single responsibility principle says that every class should do their own job like Account class should do accounting work and Employee class should maintain employee details.

 

Here is how code looks like.

 

public class SalesManager{

  public string _isActive = "";

  public bool AuthorizeMe(EmployeeCard obj){

       if(obj.AuthorizeManager(this) == true){

               return true;

       }else{
   
            return false;
        }
            
            return false;
  }


}


public class EmployeeCard{


  public bool AuthorizeManager(SalesManager obj){

      if(obj._isActive == "Y"){
         
            return true;
        
       }else{
           
            return false;
       }
	
            return false;

  }


}

class Program{

  public static void Main(string args[]) {

    SalesManager objsales = new SalesManager();
    EmployeeCard objcard = new EmployeeCard();
    objsales._isActive = "Y"; //This value can be set from database
    
        if(objsales.AuthorizeMe(objcard) == true){
              Console.WriteLine("Manager is been entered in the company");
        }else{
              Console.WriteLine("Manager is not been entered in the company")
        }

  }

}

If you see "SalesManager" class using "EmployeeCard" object to check authorization process and "EmployeeCard" uses "SalesManager" object to check whether an employee is active or not. So both entities share each others object for some work but they are not dependent on each other because we can use same "EmployeeCard" object in other departments of a company like for "SalesTeam" class, "AccountTeam" class, "Staff" class and so on and in the same way "SalesManager" object can be used in different places like for "SalesTeam" class, "ProductSales" class and so on.

So both of these entities have their own life time of object and at same time they share each other’s object for some work. The most important part is that there no single owner both entities are equal. So as you see we have successfully made an association relationship.

 

Aggregation is based on HAS-A Relationship


What is an Aggregation in C#


Aggregation is based is on "has-a" relationship principle. Here both entities meet for some work and then get separated but here one entity has to be an owner and at a same time they should be independent from each other (having own life time).  In association principle there is no owner but in aggregation any one entity should be an owner to other entity.


Now let's extract example no (4).


4. SalesManager has got SalesTeam to work under him.


In this above scenario we have two entities "SalesManager" and "SalesTeam". According to the real world scenario "SalesManager" has to be an owner to "SalesTeam" means SalesManager will only use the object of SalesTeam to display his team records and at a same time SalesTeam have own object life time means it is not dependent on SalesManager. SalesTeam can be placed under BranchHead or CompanyHead. so let me put this in the coding style.

 

public class SalesManager{

  public int Managercode = 0;
 
  SalesTeam objteam = new  SalesTeam();

  public object MyTeam(){

     return objteam.DisplayTeam(Managercode);
       
  }


}


public class SalesTeam{


 SqlConnection objconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString()); //connection is defined in app.config file

  public dataset DisplayTeam(int managercode){

            string sql = "Select * from 'salesteam' where managerid = "+managercode;
            DataSet ds = new DataSet();
            objconn.Open(); // define
            SqlCommand objcmd = new SqlCommand(sql, objconn);
            SqlDataAdapter objadp = new SqlDataAdapter(objcmd);
            objadp.Fill(ds);
            objconn.Close();
            return ds;
       
  }


}

Below code can be your windows form code or website page load code.

class Program{

  public static void Main(string args[]) {

    SalesManager objmanager = new SalesManager();
   objmanager.Managercode = 5; //this can be set from database
    dataGridView1.DataSource = objmanager.MyTeam().ToList(); 

  }

}

If you see in our above code that SalesManager class uses SalesTeam object to display records of his working team. Here SalesManager class is an owner because it uses SalesTeam object for some time and at a same time both of these classes have independent of each other. So it means we have successfully made a aggregation relationship.

If you have noted we apply aggregation in three tier architecture means in business layer class we uses data layer class object to display records and here business layer will be an owner of data layer. So this is also an aggregation relationship.

Composition is based on PART-OF Relationship - Death Relationship


Composition is a "part-of" relationship. In this relationship both entities are interdependent of each other like a human body is dependent on heart and viceversa heart is dependent on human body borh are useless without each other.


Now let's extract example no (5).


5. SalesManager has got responsibility to sell the products and to achieve the monthly target.

 


public class SalesManager{

   public int target = 10;
   private string _manageractive = "";

        public string ManagerStatus
       {
            get { return _manageractive; }
            set { _manageractive = value; }
        }

  public void PreviousMonthStatus()
  {
            int previousmonthsales = 15; // This can be set from DB

            if(previousmonthsales >= target){
            
              
                  ManagerStatus = "SalesDone";


            }else{

	     ManagerStatus = "SalesNotDone";
	
            }
  }
   
   public List LoadProductsToSell(SalesManager oManager)
   {         
            PreviousMonthStatus();

            clsProduct objProducts = new clsProduct(oManager);
            return objProducts.LoadProducts();
    }

}


public class clsProduct
{
        private SalesManager oManager;

         public clsProduct(SalesManager oMan)
        {
            oManager = oMan;
        }
	
         public string ManagerStatus
        {
            get
            {
               return oManager.ManagerStatus;
            }
        }

         public List LoadProducts()
        {
            if (ManagerStatus == "SalesDone")
            {
                DataSet ds = new DataSet();
                ds = (DataSet)objDataLayer.LoadProductsDB();

                clsProduct oProduct;

                foreach (DataRow theRow in ds.Tables[0].Rows)
                {
                    oProduct = new clsProduct(oCustomer);
                    oProduct.ProductCode = Convert.ToInt16(theRow["product_id"].ToString());
                    oProduct.ProductName = theRow["product_name"].ToString();
                    oProduct.ProductQuantity = Convert.ToInt16(theRow["product_quantity"].ToString());
                    oProduct.ProductPrice = Convert.ToDouble(theRow["product_price"].ToString());
                    lstProduct.Add(oProduct);
                }

            }

              return lstProduct;
           
            
        }


}

In our above code we have two classes "SalesManager" and "clsProduct" respectively. As we know in general sales-manager salary is dependent on product selling and product selling is also dependent on sales-manager. So both are interdependent on each other. Same way we made a composition relationship where both entities life time is dependent on each other.


If you see we cannot load any products using "clsProduct" class because we need  "SalesManager" object to check whether that "SalesManager" completed previous month target or not same way "SalesManager" class also cannot load products without "clsProduct" object and we cannot write "LoadProducts()" method in "SalesManager" because it will violate our single responsibility principle.So this is how we have successfully made composition relationship.


So this is all about relationships in object oriented programming. If you have any doubts or query kindly let me know through your valuable comment and if you like this article kindly share with your friends or colleagues. Thank you..!

Author: Gurunatha Dogi

is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server and lots more. Follow me @ and twitter.... read more

Comments

64x64
By Juan torres on 2015-09-10
How u implement a composition in main or u always work inside class that u used for work with other class then properties.

Add a Comment