Search code examples
vbacollectionsinterfacestrong-typingimplements

Is it possible to determine if two objects both implement a common interface which is not specified at compile time?


Given Object1 and Object2, are there any techniques for determining if they both implement a common interface? No problem if the interface is known at compile time (use typeof ... is [known interface]), but what about if interface isn't specified at compile time?

Specific use case is implementing a strongly typed collection object. I only want to add Object2 if it shares a common interface as Object1. Typename doesn't work since it returns the underlying object type and I may have two distinct objects each implementing ISomeInterface but on different underlying classes.

An example that doesn't quite work can be found here (as it relies on typename but that doesn't allow for interface comparisons)

Specifically, expanding the IsTypeSafe function found here on CodeReview but adapted so that if an object supports an interface common to all previously added items, it can be added to the list.

Specific question: is there a way to determine if two objects both implement a common interface that is unspecified at compile time?


Solution

  • I got really confused with your "unspecified at compile time" wording, but the crux of your question is here:

    if an object supports an interface common to all previously added items, it can be added to the list.

    In other words, you're asking if there's a way to do this in VBA (pseudo-mish-mash of VBA/C#):

    isOk = item.Type.Interfaces.Any(i => other.Type.Interfaces.Contains(i))
    

    In order to be able to inspect an object variable's implemented interfaces, you'd need to be able to inspect its type at run-time. This ability is called "reflection"... and VBA can't do that.

    Rubberduck (disclaimer: I manage this OSS VBIDE add-in project) has a COM API that might eventually grow to support exactly that though (it's open-source, implement it - we are very happy to take pull requests!), but in order to work its magic it needs to literally parse and resolve the entire project and all its references, which means using reflection for what you'd like to use it for, would be a massive performance hit.

    A "type-safe" List class in VBA is basically smokes & mirrors. Sorry!