C# does not support multiple inheritance, which means that a class cannot directly inherit from more than one base class. This is a design decision that was made to avoid the potential ambiguity and complexity that can arise from multiple inheritance.
However, C# does support something called interface inheritance, which allows a class to implement multiple interfaces. An interface defines a contract for a class, specifying a set of methods and properties that the class must implement. A class can implement multiple interfaces, but it can only inherit from a single base class.
Here's an example of a class that implements two interfaces,
public class MyClass: IInterface1, IInterface2 {
// Implementation of methods and properties from IInterface1 and IInterface2
}
In the above example, the MyClass
class implements both the IInterface1
and IInterface2
interfaces. This means that it must provide an implementation for all of the methods and properties defined by those interfaces.
While interface inheritance allows a class to provide an implementation for multiple sets of methods and properties, it does not provide the same kind of code reuse that multiple inheritance does in languages that support it.
In C#, if you want to reuse code from multiple classes, you can use composition instead of inheritance. Composition involves creating objects of the classes you want to reuse within your new class, and then delegating the relevant work to those objects. This allows you to reuse code without the potential ambiguity and complexity that can come from multiple inheritance.