O'Reilly logo

C# 2008 Programmer's Reference by Wei-Meng Lee

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. Inheritance

Inheritance is one of the fundamental concepts in object-oriented programming. Inheritance facilitates code reuse and allows you to extend the functionality of code that you have already written. This chapter looks at:

  • How inheritance works

  • Implementing inheritance in C#

  • Defining abstract methods and classes

  • Sealing classes and methods

  • Defining overloaded methods

  • The different types of access modifiers you can use in inheritance

  • Using inheritance in interfaces

Understanding Inheritance in C#

The following Employee class contains information about employees in a company:

public class Employee
{
    public string Name { get; set; }
    public DateTime DateofBirth { get; set; }
    public ushort Age()
    {
        return (ushort)(DateTime.Now.Year - this.DateofBirth.Year);
    }
}

Manager is a class containing information about managers:

public class Manager
{
    public string Name { get; set; }
    public DateTime DateofBirth { get; set; }
    public ushort Age()
    {
        return (ushort)(DateTime.Now.Year - this.DateofBirth.Year);
    }
    public Employee[] subordinates { get; set; }
}

The key difference between the Manager class and the Employee class is that Manager has an additional property, subordinates, that contains an array of employees under the supervision of a manager. In fact, a manager is actually an employee, except that he has some additional roles. In this example, the Manager class could inherit from the Employee class and then add the additional subordinates property that it requires, like this:

public class ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required