Search code examples
c#.netms-officeoffice-interop

Passing a namespace into a function


I've got a function which takes a word document and saves it in html format. I'd like to use the same function to work with any document type. I've tried using generics (I'm assumming the different doc APIs are the same) which fails due to the reason Jon Skeet pointed out. Is there another way?

using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;

//Works ok
private void convertDocToHtm( string filename )
{
... snip

     var app = new Word.Application();
     var doc = new Word.Document();
     doc = app.Documents.Open(ref fileName, ref missing, ref trueValue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

... snip    
}

//fails dismally (to compile) because 'T' is a 'type parameter', which is not valid in the given context - i.e Word is a namespace not a class
private void convertDocToHtm2<T>( string filename )
{
... snip

     var app = new T.Application();
     var doc = new T.Document();
     doc = app.Documents.Open(ref fileName, ref missing, ref trueValue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

... snip
}

//calling examples
convertDocToHtm( filename );
convertDocToHtm2<Word>( filename );
convertDocToHtm2<Excel>( filename );

Solution

  • No, this isn't possible. Type parameters are for types, not namespaces.

    In particular, the compiler couldn't verify that such a type even existed - you could call ConvertDocToHtm2<System> for example.

    With dynamic typing in C# 4, you could do something this:

    private void ConvertDocToHtm2<TApplication>(string filename)
        where TApplication : new()
    {
         dynamic app = new TApplication();
         dynamic doc = app.Documents.Open(filename, html: trueValue);
         // Other stuff here
    }
    

    Then:

    ConvertDocToHtm2<Word.Application>(filename);
    

    (I've guessed at the parameter name for trueValue by the way - you'd want to verify that.)