C# conditional reference in solution

Viewed 68

I am developing a C# application which uses a .tlb file as reference in its solution, which should be installed by another application - however I've recently discovered such use cases, where this other application would not be installed. In these cases my program fails to run correctly, my installer (made with Microsoft Installer Projects) throws the following error:

enter image description here

I suspect the behavior above is due to an initializer subclass which is called by the installer. I want this initializer class only call the discussed .tlb as reference, if it is actually useable/installed - so in case it's actually there, since it is only related to that other application which would install it to the user computer. How can I achieve this "conditional referencing" in my initializer.cs?

The exact code part:

using NGOptMan // This should be conditional or the line actually using it;
...
var optMan = (IOptionsManager)Activator.
 CreateInstance(Type.GetTypeFromProgID("SIDEXISNG.OptionsManager")); 
 // This is the only command where I would use this .tlb.
1 Answers

You can make use of dynamic which allows you to utilise COM objects but without a type library.

Change:

var optMan = (IOptionsManager)Activator.CreateInstance(...)

to

dynamic foo = Activator.
 CreateInstance(Type.GetTypeFromProgID("SIDEXISNG.OptionsManager")); 

if (foo == null)
    return;  // failed

// Success
var optMan = (IOptionsManager)foo;  // Now cast using the typelib
  

NOTE the use of dynamic and the removal of the cast.

Related