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.
You can use an interface to accomplish what you want to do.
interface IConnectable
{
void Connect();
void Disconnect();
}
Both A
and B
should implement IConnectable
. Then use IConnectable
instead of Object
as the parameter type for your method and you should be all set.
public void MakeConnection(IConnectable connectable)
{
connectable.Connect();
// Do some more stuff...
connectable.Disconnect();
}
Edit: Since you don't have the source code, you have a couple of options:
dynamic
keyword, (if you are using .NET 4.0)if
/else
statements A
and B
and have them implement the interface (or use common abstract base class for them)For example:
class AWrapper : IConnectable
{
private A obj;
public AWrapper(A obj)
{
this.obj = obj;
}
public void Connect()
{
this.obj.Connect();
}
public void Disconnect()
{
this.obj.Disconnect();
}
// other methods as necessary
}
(BWrapper
would be similar, just using B
instead of A
)
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.
If the interface solution is not possible (e.g you don't have source code), another less effecient solution is to use reflection.
As others have said, re-factoring to use interfaces or using the dynamic approach are probably the most elegant ways.
If this is not possible you could cast the object to your types. I'd suggest using as
and then checking that the cast worked, an unchecked cast would be dangerous if someone called this with a type that failed to cast.
E.g. If types A
and B
both have a method called DoSomething()
then this will work...
public static void CallDoSomething(object o)
{
A aObject = o as A;
if (aObject != null)
{
aObject.DoSomething();
return;
}
B bObject = o as B;
if (bObject != null)
{
bObject.DoSomething();
return;
}
}
BUT this is pretty ugly to be honest... I'd really try and refactor to interfaces.