How do you establish multiple inheritance in C#?

Multiple inheritance is where an entity extends behavior of more than one entity. In Java, you establish multiple inheritance through classes because a class can inherit from more than one class. But in C#, a class can inherit from only one class.



Then how do you establish multiple inheritance in C#? You can achieve it using interfaces. In C# though a class can inherit from only one class, the same class can implement more than one interface. Here is an example demonstrating multiple inheritance in C# using interfaces:

interface sampleInterface1 {
void sampleMethod1();
}
interface sampleInterface2 {
void sampleMethod2();
}
class sampleClass:sampleInterface1,sampleInterface2 {
void sampleMethod1() {
Console.WriteLine(“Extending sampleMethod1of sampleInterface1”);
}
void sampleMethod2() {
Console.WriteLine(“Extending sampleMethod2 of sampleInterface2”);
}
}
class testClass {
public static void Main() {
sampleClass obj = new sampleClass();
obj.sampleMethod1();
obj.sampleMethod2();
}
}

Output of this code will be:

Extending sampleMethod1of sampleInterface1
Extending sampleMethod2 of sampleInterface2

| Can you call a constructor from another constructor of the Class in .NET? | Difference between Response.Output.Write() method and Response.Write() method in .NET | How do you establish multiple inheritance in C#? | How do you introduce a ReadOnly property in C#? | How do you perform constructor overloading in C#? | Is catch(Exception) recommended to be used in .NET? | What are the different access modifiers available in C#? | What are the different ways of overloading in C#? | What are the members of stringbuilder class in C#? | What is Multicast Delegate? Explain it with example in C# | What is the difference between abstract class and interface in .NET? | What is the difference between Clone and CopyTo methods in .NET | What is the difference between const and readonly in .NET | What is the difference between directcast and ctype in .NET? | What is the difference between out and ref parameters in .NET | What is the difference between public assembly and private assembly in .NET | What is the difference between strong typing and weak typing in .NET? | What is the difference between Trace and Debug in .NET | What is the need for Abstract Factory Pattern in C#? | What is the need for Adapter Pattern in C# |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.