C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
ListFinally: 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();
}
}
}
Output
Perl.Act
Python.Act
Info: You can implement multiple interfaces. You can combine concepts—both implement interfaces and inherit from a single base class.
InterfaceIEnumerableC# program that causes compile-time error
class Net
{
}
class Perl : Net
{
}
class Python : Net, Perl
{
}
class Program
{
static void Main()
{
}
}
Output
Error CS1721
Class 'Python' cannot have multiple base classes: 'Net' and 'Perl'
Tip: It is often better to introduce a new virtual method on the base class and implement it in the derived type.
AsIsVirtual