Let’s say you have two different C# classes A and B that while not deriving from the same base class do share some of the same names for methods. For example, both classes have a connect and a disconnect method, as well as several others. I want to be able to write code once that will work with both types.
Here is a simplified example of what I would like to do:
public void make_connection(Object x)
{
x.connect() ;
// Do some more stuff...
x.disconnect() ;
return ;
}
Of course, this does not compile as the Object class does not have a connect or disconnect method.
Is there a way to do this?
UPDATE. I should have made this clear from the start: I only have the DLLs for A and B and not the source.
You can use an interface to accomplish what you want to do.
Both
AandBshould implementIConnectable. Then useIConnectableinstead ofObjectas the parameter type for your method and you should be all set.Edit: Since you don’t have the source code, you have a couple of options:
dynamickeyword, (if you are using .NET 4.0)if/elsestatementsAandBand have them implement the interface (or use common abstract base class for them)For example:
(
BWrapperwould be similar, just usingBinstead ofA)Then you could create the wrappers and pass them into
MakeConnection. It’s up to you how you want to do it. Depending on your situation, one method may be easier than the others.