In this article I am trying an alternative approach for Multiple Inheritance. In C sharp Multiple Inheritance is not possible to achieve this is well known. i.e. You cannot inherit from two classes. Program : ClassA , ClassB // This cannot be achieved { } So lets try an alternative approach where we can leverage the advantages of Multiple Inheritance . Please note that I have not used Reflection in this example , that is not the scope of this article . Consider ClassA and ClassB as the two classes whose functionality we need to access . class ClassA { public string member { get; set; } public ClassA() { Console.WriteLine("A constructor is called"); member = "Member of ClassA"; } public void display() { Console.WriteLine("Display A"); } }
class ClassB { public string member { get; set; } public ClassB() { Console.WriteLine("B constructor is called"); member = "Member of ClassB"; } public void display() { Console.WriteLine("Display B"); } } Creating a Router : Let us create a Router Interface . interface IRouter { void display(string param); } The Router class looks as follows : class Router : IRouter { public string member { get; set; }
public Router(string param) { if (param == "A") { new ClassA(); member = new ClassA().member; } else if (param == "B") { new ClassB(); member = new ClassB().member; } }
public void display(string param) { if (param == "A") { new ClassA().display(); } else if (param == "B") { new ClassB().display(); } } }
class Program { static void Main(string[] args) { IRouter router = new Router("A"); router.display("B"); Console.Read(); } } The following output is displayed : Conclusion This is a simple Router which routes the method calls to Respective classes based on the User Input. Hopefully it would be useful. Thanks .
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: