#744 – The Purpose of Inheritance
December 26, 2012 3 Comments
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 .."); } }
I think this is a bad example of inheritance. Using new brings issues when you treat the QuietDog as a Dog. Add virtual to the main Bark method in the Dog class and then replace new with override in the QuietDog class instead.
Cheers,
Imar
You’re right–new keyword leads to problems when treating the object as an instance of the base class. (See https://csharp.2000things.com/2012/09/28/681-avoid-using-the-new-keyword-to-hide-methods/ ). So you might argue to never use the new keyword. But there are cases when you do want to use it, to make explicit the fact that you do not want the object to behave polymorphically (see https://csharp.2000things.com/2012/10/01/682-the-real-reason-for-the-new-keyword/).
I agree with all that; I just brought this up because you’re using “new” on the page that says: “The Purpose of Inheritance”. You’re hardly discussing inheritance here or go into detail of its purpose, and don’t show the real implementation using virtual etc, and then spend the majority of the post and code showing how to “break” inheritance which you should only do in special cases.
That’s all; other than that: great work.
Cheers,
Imar