1

I have a pair of COM objects in two different places that follow the exact same interface (except for namespace, so nsA.ICOMObject looks the same as nsB.ICOMObject with the exception that nsA is replaced by nsB all over the place).

Which of the objects I will be using is decided on application startup and can be held easily enough. The issue that I have is how to do all of this without duplication. I know that for method calls I can do it simply with a dynamic object but that still leaves me an issue with event handling.

Currently I would do:

if (useObjectA)
{
    theCOMObject.eventToHandle += new nsA.eventHandler(method);
}
else
{
    theCOMObject.eventToHandle += new nsB.eventHandler(method);
}

all over the place and for just a namespace change this seems a little silly.

Am I right that there is an easier way to do this and what is it? There are literally hundreds of methods/properties/events on these objects so creating an object that takes all the pain away would be very hard work.

Many Thanks

Gareth

noseratio
  • 59,932
  • 34
  • 208
  • 486
ridecar2
  • 1,968
  • 16
  • 34
  • Isn't that exactly what an interface is for? when you state **the exact same interface** isn't that just going to be `ICOMObject.eventToHandle`? – James Mar 19 '15 at 11:58
  • I agree, the issue is that the interfaces are the same except for they reside in different namespaces and contain references to classes in their respective namespaces that are the same. – ridecar2 Mar 19 '15 at 12:00
  • 1
    So the interfaces are not the same at all. This can't get better until you go back to the COM object implementation itself and make them use the exact same interface declaration. Not only does that allow you to treat them the same in your program, it is also a hard guarantee that these interfaces will *forever* be the same. If you didn't create these COM objects then the weapon of choice is a telephone. – Hans Passant Mar 19 '15 at 12:05
  • @HansPassant I wish I were working in a nice dynamic language here, then it would all work nicely for me. Given that we have dynamic in C#4 is there really no nice way of doing this? Seems like a massive issue to me if that's the case. – ridecar2 Mar 19 '15 at 12:20
  • ridecar2. The issue is that you're asking for duck Typing, there's no guarantee that the interfaces support the same methods with the same signatures. Are you restricted by framework? [as dynamic would probably work in this case.](http://stackoverflow.com/questions/21278078/what-is-interface-duck-typing). – James Mar 19 '15 at 12:39
  • Could the person who downvoted please comment as to why the downvote so that I may ask better questions (or ask questions better) in future? – ridecar2 Mar 19 '15 at 13:52
  • Do `nsA.ICOMObject` an `nsB.ICOMObject` still deal with the same COM object (same CLSID?) – noseratio Mar 22 '15 at 00:39
  • Unfortunately they do not, the COM objects are in different files too. – ridecar2 Mar 23 '15 at 06:10

0 Answers0