C# InheritanceReview the concept of inheritance. See a class that inherits from another.
dot net perls
Inheritance. With inheritance, we build several types upon a common abstraction. Then we later act upon all those types through the abstraction.
Inheritance benefits. Inheritance makes programs simpler and faster. But it must be used with care. We examine inheritance and polymorphism.
Example. When you specify that a class derives from another class, the class you create acquires all the features of the base class. We "build" upon the base class.
Base class The class another class inherits from. In the C# language, the ultimate base class is the object class.
Derived class The class with a base class. A derived class may have multiple levels of base classes.
Example This code shows 2 derived classes from 1 base class. We create a List of the base class type, and then add derived classes to it.
Finally We call Act() through the base class references. This invokes the overridden functions through the virtual base function.
C# program that uses base class, virtual method
using System; using System.Collections.Generic; class Net { public virtual void Act() { } } class Perl : Net { public override void Act() { Console.WriteLine("Perl.Act"); } } class Python : Net { public override void Act() { Console.WriteLine("Python.Act"); } } class Program { static void Main() { // Use base class and derived types in a List. List<Net> nets = new List<Net>(); nets.Add(new Perl()); nets.Add(new Python()); // Call virtual method on each instance. foreach (Net net in nets) { net.Act(); } } }
Perl.Act Python.Act
Error, multiple bases. You cannot specify multiple base classes on a type declaration. This restriction was imposed on the C# language to reduce the complexity of inheritance.
Info You can implement multiple interfaces. You can combine concepts—both implement interfaces and inherit from a single base class.
C# program that causes compile-time error
class Net { } class Perl : Net { } class Python : Net, Perl { } class Program { static void Main() { } }
Error CS1721 Class 'Python' cannot have multiple base classes: 'Net' and 'Perl'
Casting. We can use casts to convert a base type to a more derived type. If a program uses a base class but has to cast to more derived types, it may have a design flaw.
Tip It is often better to introduce a new virtual method on the base class and implement it in the derived type.
A summary. Inheritance enables you to create complex models that can reduce your program size and improve its modularity and performance.
A final note. It is important not to overuse inheritance. Simpler solutions, where a common abstraction is not specified, can be superior.
© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.