Hi @Tom Meier , Welcome to Microsoft Q&A,
There is no way to write multiple inheritance in C# classes.
What you are after is polymorphism. Polymorphism is another important concept in object-oriented programming, which allows different subclasses of objects to respond differently to the same method. Polymorphism implements the feature of "one interface, multiple implementations", which can increase the flexibility and scalability of the code.
In C#, polymorphism can be achieved through method override and interface. When a subclass overrides a virtual method of its parent class or a method that implements an interface, these methods can be called through a reference to the parent class or interface, and which method to call is determined based on the actual object type.
For example:
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal makes a sound.");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Dog barks.");
}
}
class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Cat meows.");
}
}
class Program
{
static void Main(string[] args)
{
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.MakeSound(); // Output: Dog barks.
animal2.MakeSound(); // Output: Cat meows.
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.