#744 – The Purpose of Inheritance

Inheritance in C# (and .NET) is the idea of designing a class that reuses the implementation of an existing class.

The primary purpose of inheritance is to reuse code from an existing class.  Inheritance allows you to create a new class that starts off by including all data and implementation details of the base class.  You can then extend the derived class, to add data or behavior.

You can also use inheritance to modify the behavior of an existing class.  The code below shows a QuietDog class that does everything that a normal Dog does, but barks quietly.

    public class Dog
    {
        public string Name { get; set; }

        public void Bark()
        {
            Console.WriteLine("Woof");
        }

        public void Fetch()
        {
            Console.WriteLine("Fetching !");
        }
    }

    public class QuietDog : Dog
    {
        public new void Bark()
        {
            Console.WriteLine(".. silence ..");
        }
    }
Advertisements