Click here to Skip to main content
15,353,432 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello All,

Recently i was asked a question in one of the interviews:

There is a dll, which has 2 classes
C#
Class A
{
Method A(){...}
}

Class B
{
Method B(){...}
}


In a separate program there is another Class C
Now how can i inherit both CLass B & A in Class C, without modifying anything in the dll?

So how to achieve this?
Please help me in getting the answer to this silly question.

What I have tried:

As multiple inheritance is not supported in C# so I cannot give Class C:B,A
And as i cannot modify anything in the dll, i cannot implement interfaces too..
Posted
Updated 13-Jul-16 23:13pm

Depends.
You could say: not at all, as multiple inheritance does not exist in C#.
You could say: let's use some tricks. Like that:
C#
Interface IA
{
    Method A();
}
Interface IB
{
    Method B();
}

Then let's add some wrappers which implement the interfaces and just pass thru to the original classes:
C#
class AWrapper : IA
{
    A _Instance;
    AWrapper()
    {
        _Instance = new A();
    }

    Method A ()
    {
        _Instance.A();
    }
}
and similar for B.
Now we can change C:
C#
class C: IA, IB
{
    IA _AInstance;
    IB _BInstance;
    C()
    {
        _AInstance = new AWrapper();
        _BInstance = new BWrapper();
    }

    Method A()
    {
        _AInstance.A();
    }

    Method B()
    {
        _BInstance.B();
    }
}
Well, not exactly inheritance, rather aggregation.
   
Comments
[no name] 15-Jul-16 5:12am
   
the trick which you suggested, i told the same thing but he simply rejected it saying no you cant modify anything in the dll. So, i left with no options..

For this mere question, he rejected me despite me saying that its not possible. :(
Bernhard Hiller 18-Jul-16 3:23am
   
That doesn't modify anything in the external dll. So: be glad he rejected you so quickly, that's better than to learn later that he's a moron...
My answer would be that you can't. Some interviewers will ask you these kinds of questions to test your confidence and see if you have genuine knowledge or are just trying to game the interview process.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900