switching alias at runtime

Is it possible to reset an alias at runtime Eg if I have

using Office = Microsoft.Office.Interop.Word;

Can I make this Office = Microsoft.Office.Interop..Excel from code

Thanks&Regards,
Pavan



Answer this question

switching alias at runtime

  • Hans Guan

    Thanks for your time!

    Actually i've to deal with two versions of WOrd interop. I've to use one of the interops depending on the office version installed. There are definitely ways for this like using late binding, wrapping the whole implementation in an interface (i guess this is one of the design patterns), casting all the objects into "object" and then re-csting beased on the office installtion etc.

    But i was wondering if I could set an alias at runtime. this makes my sol very simple. everywhere i've to use a Word object i do it using the alias. Initially when my addin runs i detect the version at runtime and set the alias to the appropriate namespace. this would involve minimum changes in my code I know its sort of a weird idea but thought to give it a try.


  • Brian.Webb

    What would be the point changing alias at runtime Aliases are just to make the code more readable. After compilation, there is no such namespace as "Office" in your CIL code, just Microsoft.Office.Interop.Word and Microsoft.Office.Interop.Excel namespaces, even if you use aliases to change their names.

    So answer for your question is simply "No, you cannot", since aliases does not exist outside your source code.

    If you need to use same methods to handle word and excel objects (as i think you wish), you should consider using delegates or some base class object to reference to both word and excel objects (if there is any suitable, i am not familiar with office objects).

  • Mike Whyte

    I think it would be the best to make an abstract class, for example "WordClass" or such, and implement concrete Word-classes for each Word version in separate dll's. Then you in your program inspect the version of the existing Office, and dynamically load the right concrete Word-class.

    WordClass myWord = null;

    if( wordVersion == 2003)
    {
    myWord = DynamicallyLoadWord2003Dll();
    }
    else if( wordVersion == 2005)
    {
    myWord = DynamicallyLoadWord2005Dll();
    }

    Of course this is not necessary, but in some cases the loading of unsupported components cause strange problems. In one Windows Mobile application, I had to dynamically load POOM-wrappers, because in Pocket PC 2003 the disposing of the (unsupported) Managed POOM API caused the Garbage Collector to throw exceptions (even if i did not even create POOM objects!). A hard thing to catch, don't you think ;)

  • switching alias at runtime