tags:

views:

130

answers:

3

I'm working with MS Excel interop in C# and I don't understand how this particular line of code works:

var excel = new Microsoft.Office.Interop.Excel.Application();

where Microsoft.Office.Interop.Excel.Application is an INTERFACE defined as:

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

I'm thinking that some magic happens when the interface is decorated with a CoClass attribute, but still how is it possible that we can create an instance of an interface with a new keyword? Shouldn't it generate a compile time error?

+2  A: 

Actually code that you mentioned created instance of the ApplicationClass class and that is what CoClass attribute does.

See this answer for details: http://stackoverflow.com/questions/1093536/how-does-the-c-compiler-detect-com-types/1093623#1093623

Andrew Bezzub
+1 I'd agree with that.
amelvin
+3  A: 

Ayende blogged about this.

Darin Dimitrov
+1 Interesting blog, but I may not be rushing out to use it. It feels like an adaptor patter applied to an interface (if that makes any sense!).
amelvin
A: 

ApplicationClass is implement Application interface. In two words, interface is declaration of methods of class. Your line of code create instance of class ApplicationClass (because interface have attribute with class with constructor), query this instance of interface Application and put this to variable excel.

On second question: no, you can't create interface with 'new' keyword. Because, any interface have only declaration of methods, not implementation. You can try this for creating you own classes and interfaces:

interface MyIntf {
   void method1(string s1);
}

public class MyIntfImplementation : MyIntf {

   void method1(string s1) {
     // do it something
   }
}

After this you can use this:

MyIntf q = new MyIntfImplementation();
q.method1();