4

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?

3 Answers 3

4

Ayende blogged about this.

Sign up to request clarification or add additional context in comments.

1 Comment

+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!).
3

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

See this answer for details: How does the C# compiler detect COM types?

Comments

1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.