articles

Home / DeveloperSection / Articles / Inheritance in C Sharp

Inheritance in C Sharp

Anonymous User5339 17-Jul-2010

Inheritance allows us to reuse existing code which saves time. It is basic concept of

Object Oriented Programming (OOPS).

Here, I am going to demonstrate the use of inheritance through an example.

Example

 Inheritance in C Sharp

//creating instance ofchild class
designation de = new designation();
       
 private void btnAdd_Click(object sender, EventArgs e)
   {
//calling assign() function of parent class through child class
  de.assign(int.Parse(txtID.Text),txtName.Text.Trim(), txtAddress.Text.Trim(), txtDOB.Text.Trim());
 
//calling function of child class
     de.assign(txtDesig.Text.Trim(),txtBranch.Text.Trim());
    }
 
private void btnParent_Click(object sender, EventArgs e)
  {
//calling parent class display() method through instance of child class by type casting child class to //parent class.
    ((employee)de).display();
  }

 Inheritance in C Sharp

 

 private void btnChild_Click(object sender, EventArgs e)
   {
//calling display() method of child class
       de.display();
    }

 Inheritance in C Sharp

//creating parent class ‘employee’
    public class employee
    {
        int id;
        string name;
        string address;
        string dob;
//constructor to initialize variables
        public employee()
        {
            id= 0;
            name= null;
            address= null;
            dob= null;
        }
 
        public void assign(int i, string n, string add, string d)
        {
//assigning values to variables
            id= i;
            name= n;
            address= add;
            dob= d;
        }
 
        public void display()
        {
//displaying values
            MessageBox.Show("ID: " +id.ToString() + "\nName: " + name + "\nAddress:" + address + "\nDateof Birth: " + dob,"Parent");
        }
    }
 
//creating child class ‘designation’ which will inheret ‘employee’. To inheret parent class we use colon (:)
    public class designation : employee
    {
        string desig;
        string branch;
 
        public designation()
        {
            desig= null;
            branch= null;
        }
 
        public void assign(string d, string b)
        {
//assigning values to variables of child class
            desig= d;
            branch= b;
        }
 
        public new void display()
        {
//calling display() method of base class
            base.display();           
//displaying values of variables of child class
            MessageBox.Show("Designation: " + desig + "\nBranch: " + branch,"Child");
        }

 


Updated 04-Mar-2020
I am a content writter !

Leave Comment

Comments

Liked By