• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Tuesday, August 1, 2017

OOPS – Inheritance in C#

 Abhishek Tomer     August 01, 2017     .Net, C#     No comments   

In our previous post of OOPS we have learned a lot of differences and similarities between a Class and a struct.
Today we are going to learn about one of the primary pillar of OOPS i.e Inheritance.
So let's start with the overview.

Overview: - Inheritance is one of the four primary characteristics (or pillars) of object-oriented programming. Inheritance provide the capabilities to add new feature in a class by using existing class.

Inheritance allow us to create new classes that can be reuse, extend, and modify the behavior that is already defined in other classes.

A class whose members are inherited is called the base class/parent class/super class, and the class that is inherits those members base class is called the derived class/child class/sub class.
For Example: - Animal is a base class and Dog, Cow etc. are the child or derived classes.

Advantage: -
  • Provides code reusability.
  • Reduces source code size and improves code readability.
  • Code is easy to manage and divided into parent and child classes.
  • Supports code extensibility by overriding the base class functionality within child classes.
Disadvantage: -
  • In Inheritance base class and child classes are tightly coupled. Hence If you change the code of parent class, it will get affects to the all the child classes.
  • In class hierarchy many data members remain unused and the memory allocated to them is not utilized. Hence affect performance of your program if you have not implemented inheritance correctly.
Example: -In this example we can see the parent child relationship.

//Base Class
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public DateTime DateofBirth { get; set; }
    }

    //Child Class1
    public class PermanetEmployee : Employee
    {
        public double SalaryPerDays { get; set; }
        public int WorkingDays { get; set; }
        public double getPermanetEmployeeSalary()
        {
            return SalaryPerDays * WorkingDays;
        }
    }
    //Child Class2
    public class ContactEmployee : Employee
    {
        public double SalaryPerHours { get; set; }
        public int WorkingHours { get; set; }
        public double getContactEmployeeSalary()
        {
            return SalaryPerHours * WorkingHours;
        }
    }

    public static class Test
    {
        static void Main(string[] args)
        {
            PermanetEmployee permanetEmployee = new PermanetEmployee();
            //reusable code
            permanetEmployee.ID = 1;
            permanetEmployee.Name = "Tom";
            permanetEmployee.Email = "tom@test.com";
            permanetEmployee.DateofBirth = DateTime.Now;

            //new code for Permanet Employee
            permanetEmployee.SalaryPerDays = 1400;
            permanetEmployee.WorkingDays = 28;

            var PermanetEmployeeSalary = permanetEmployee.getPermanetEmployeeSalary();
            Console.WriteLine("PermanetEmployee Salary:{0}", PermanetEmployeeSalary);

            ContactEmployee contactEmployee = new ContactEmployee();
            //reusable code
            contactEmployee.ID = 1;
            contactEmployee.Name = "Tom";
            contactEmployee.Email = "tom@test.com";
            contactEmployee.DateofBirth = DateTime.Now;

            //new code for contract Employee
            contactEmployee.SalaryPerHours = 100;
            contactEmployee.WorkingHours = 54;
            var ContactEmployeeSalary = contactEmployee.getContactEmployeeSalary();
            Console.WriteLine("ContactEmployee Salary:{0}", ContactEmployeeSalary);
            Console.ReadKey();
        }
    }
Output:
PermanetEmployee Salary:39200
ContactEmployee Salary:5400
OOPS – Inheritance in C#
Salaries of each Employee type
Type of Inheritance
  • Single inheritance
  • Multi-level inheritance
  • Hierarchical inheritance
  • Hybrid inheritance
Important Keyword used in Dot Net Inheritance concept

Virtual Keyword
It used to allow a method can be overridden by child classes.
example:
public virtual int myValue()
        {
            //To DO

        }

Override Keyword
It used to override the parent class method when method declared under abstract class method or marked as virtual in normal parent class. It is also known as Method overriding.
example:
public override int myValue()
        {
            //To DO
        }

Base Keyword
It used to calls parent class method from child class for overriding functionality.
example:
public void int myValue()
        {
            base.NewValue();
        }

New Keyword
Used to hide the base class member when a method name and signature is same in parent as well child class. It is also known as Method hiding.
example:
public new int myValue()
        {
            //To DO
        }

Basic and Important Rules of Inheritance
public class OverridingDemo1
    {
        static void Main(string[] args)
        {
            //Case:-1
            ParentClass p1 = new ParentClass();
            p1.ParentMethod();                      //valid
            p1.ChildMethod();                      //invalid: because by base class object we can not call child class member.

            //Case:-2:by child class object we can called parent class member and parent class member
            ChildClass c1 = new ChildClass();
            c1.ParentMethod();                      //valid
            c1.ChildMethod();                       //valid.

            //Case:-3:
            ParentClass pc = new ChildClass();      //parent class variable can hold the reference of child class
            pc.ParentMethod();                      //valid
            pc.ChildMethod();                       //invalid: because by parent class object we can not call child class member.

            //Case:-4:
            ChildClass cp = new ParentClass();      //child class variable can hold the reference of parent class
        }
    }

public class ParentClass
    {
        public void ParentMethod()
        {
            Console.WriteLine("ParentClass with ParentMethod() is called");
        }
    }

public class ChildClass : ParentClass
    {
        public void ChildMethod()
        {
            Console.WriteLine("ChildClass with ChildMethod() is called");
        }
    }
Summary:
So, Guys that's all about Inheritance in C#. In our next post we will be learning Polymorphism and its types.

I Hope in this post I have covered all the points about Inheritance which will be helpful to you.

Please share this post with your friends and colleagues.
For any queries please post a comment below.

Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape