implement Composition & Inheritance in C# with Code with Classes
https://www.saqibsomal.com/c-sharp/implement-composition-inheritance-in-c-with-code-with-classes/13
implement Composition & Inheritance in C# with Code with Classes
A âWikiâ style definition: âobject composition (not to be confused with function composition) is a way to combine simple objects or data types into more complex ones.â
My definition: Allowing a class to contain object instances in other classes so they can be used to perform actions related to the class (an âhas aâ relationship) i.e., a person has the ability to walk.
Another âWikiâ style definition: inheritance is a way to form new classes (instances of which are called objects) using classes that have already been defined.
My definition: One class can use features from another class to extend its functionality (an âIs aâ relationship) i.e., a Car is a Automobile.
 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Composition
public partial class Form1 : Form
public Form1()
InitializeComponent();
private void button1_Click(object sender, EventArgs e)
Car c1;
c1 = new Car();
MessageBox.Show(c1.printCompleteDetails());
private void button2_Click(object sender, EventArgs e)
Animal animal = new Animal();
animal.Greet();
Dog dog = new Dog();
dog.Greet();
private void button3_Click(object sender, EventArgs e)
Cat c1=new Cat();
c1.Greet();
private void button4_Click(object sender, EventArgs e)
SavingAcc s1 = new SavingAcc(1, âAyub khanâ, 100000);
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Composition
class Person
string Pid;
string Pname;
int age;
public Person(string a, string b, int c)
Pid = a;
Pname = b;
age = c;
public string printPerson()
string ayub;
ayub = Pid + â â + Pname + â â + Convert.ToString(age);
return ayub;
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Composition
class Car
string make;
string model;
Person driver;
public Car()
make = âHondaâ;
model = âCivicâ;
driver = new Person(â122-0999â, âSaqib Somalâ, 22);
public string printCompleteDetails()
string ayub;
ayub = make + â â + model + â â + driver.printPerson();
return ayub;
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Composition
class Animal
public virtual void Greet()
MessageBox.Show(âHello, Iâm some sort of animal!â);
class Dog : Animal
public override void Greet()
MessageBox.Show(âHello, Iâm a dog!â);
class Cat : Animal
public override void Greet()
base.Greet();
class Account
int aid;
string aname;
int abalance;
public Account(int a, string b, int c)
aid = a;
aname = b;
abalance = c;
MessageBox.Show(âAccount object createdâ);
class SavingAcc : Account
public SavingAcc(int a, string b, int c):base(a,b,c)