Home > DeveloperSection > Articles > Inheritance in C Sharp

Inheritance in C Sharp

C# C# 
0 Comment(s)
 2974  View(s)
Rate this:

Inheritance in C#.Net

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.


//creating instance of child 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.




        private void btnChild_Click(object sender, EventArgs e)


//calling display() method of child class



//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 + "\nDate of 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


//displaying values of variables of child class

            MessageBox.Show("Designation: " + desig + "\nBranch: " + branch,"Child");


Don't want to miss updates? Please click the below button!

Follow MindStick