0

So i was reading this article[1], and there's a section "To declare a method that exports account information to Excel" with the following example:

using Excel = Microsoft.Office.Interop.Excel;
...
static void DisplayInExcel(IEnumerable<Account> accounts)
{
   var excelApp = new Excel.Application();
   ...
}

Excel.Application is an interface. How is this possible?

I thought interfaces weren't instantiable. Thanks!

[1] https://msdn.microsoft.com/en-us/library/dd264733.aspx

Paolo Maresca
  • 7,396
  • 4
  • 34
  • 30
Joaquin
  • 9
  • 2
  • 1
    It's intantiating an object that implements that interface but is returning it typed as the interface. – Dave Zych Oct 19 '15 at 22:36

1 Answers1

0

Indeed Excel.Application() is not instanciation but rather a property witch type is Application Interface. So how is instantiated, well it's thanks to the following Attributes

[CoClass(typeof(ApplicationClass))]. 

ApplicationClass implement Application(interface) and returns a property of type of Application interface.

[CoClass(typeof(ApplicationClass))]
[Guid("000208D5-0000-0000-C000-000000000046")]
public interface Application : _Application, AppEvents_Event
{
}

Take a look at this code.

private static void DisplayInExcel(IEnumerable<string> accounts)
{
  var excelApp = new Excel.Application{};    
}

it works too. it is not magic!

I hope it helps