articles

Home / DeveloperSection / Articles / Inheritance in C#

Inheritance in C#

Inheritance in C#

Anonymous User 4609 05-May-2016

Inheritance means parent class property access child class like methods, members etc, and also reused code, reason for using Inheritance is desirable because we can avoid writing code over and over again.

Any class can inherit more than one class or interface, that means we can inherit data and functions from multiple base classes and interfaces. 

For example: 

Shape class 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace OoopsConcepts
{
    class Shape
    {
        protected int width;
        protected int height;       
 
        public void setWidth(int w)
        {
            width = w;
        }
        public void setHieght(int h)
        {
            height = h;
        }       
    }
}

Create a another class Rectangle and inherit to shape class.

Rectangle class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace OoopsConcepts
{
    class Rectangle:Shape
    {
        public int getArea()
        {
            return (width * height);
        }
        public int getPerimeter()
        {
            return 2*(width + height);
        }       
    }
}

 And create entry point class(RectangleTest) create object of the rectangle class call the method---- 

RectangleTest class 

using System;                                               
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace OoopsConcepts
{
    class RectangleTest
    {
        static void Main(string[]args)
        {
            // Inhertance Test          
            Rectangle rectange = new Rectangle();
           // Console.Write("")
            rectangle.setWidth(10);
            rectangle.setHieght(5);
            Console.WriteLine("Total area : {0}", rectangle.getArea());
            Console.WriteLine("Perimeter : {0}", rectangle.getPerimeter());
            Console.ReadLine();
        }
    }
}


Updated 27-Nov-2019
I am a content writter !

Leave Comment

Comments

Liked By