arbitrarystringofletters arbitrarystringofletters - 3 months ago 10
C# Question

Is there a way to avoid redundant "using" directives when I only want to use an alias some of the time?

I've been writing a lot of code that works with Windows Forms and Excel Interop recently. One of the things that I've encountered is ambiguous references. For example, if I try to create a new Excel application, it doesn't work.

Application app = new Application { Visible = true };


This line returns an error because the reference to Application is ambiguous. It could refer to an Excel application, but it could also refer to a Windows Forms application.

Instead of typing this out:

Microsoft.Office.Interop.Excel.Application = new Microsoft.Office.Interop.Excel.Application { Visible = true };


I know I can just change my using directive to this:

using Excel = Microsoft.Office.Interop.Excel;


and then change my declaration of app to:

Excel.App app = new Excel.App { Visible = true};


However, later on in my code, I have to declare quite a few worksheets and workbooks. Without using the "Excel = Microsoft..." namespace alias, I could just do this since the references to Workbook and Worksheet aren't ambiguous:

Workbook someWorkbook = app.Workbooks.Add();
Worksheet someWorksheet = app.ActiveSheet;


But when I change my using directive to

using Excel = Microsoft.Office.Interop.Excel;


I have to change all declarations that use Excel objects to "Excel.someObject", or I have to add a second using directive:

Option 1:

using Excel = Microsoft.Office.Interop.Excel;
...
Excel.Application app = new Application { Visible = true };
Excel.Workbook someWorkbook = app.Workbooks.Add();
Excel.Worksheet someWorkSheet = app.ActiveSheet;


Option 2:

using Excel = Microsoft.OFfice.Interop.Excel;
using Microsoft.Office.Interop.Excel;
...
Excel.Application app = new Application { Visible = true };
Workbook someWorkbook = app.Workbooks.Add();
Worksheet someWorkSheet = app.ActiveSheet;





I much prefer Option 2, and this is me being pedantic, but the redundancy of having to write two using directives to refer to the same library is irksome. Is there a third option that allows me to write my declarations as seen in option 2 without having to use two using directives? That is, is there a way to write my using directive such that the alias can be used where needed but omitted where references aren't ambiguous?

Answer

If you are in a file that does not need to refer to System.Windows.Forms.Application (most files in your project should be like that), add using Microsoft.Office.Interop.Excel at the namespace level:

using System.Windows.Forms;

namespace TestForms {

    using Microsoft.Office.Interop.Excel;

    class TestClass {
        Application app = ... // This refers to Microsoft.Office.Interop.Excel.Application
    }

}

This way Microsoft.Office.Interop.Excel.Application would "win" over System.Windows.Forms.Application for all classes that follow using declaration.