13

I'm very surprised after seeing that I actually have to Instantiate an Interface to use the Word Interoop in C#.

Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

The Microsoft.Office.Interop.Word.Application according to what its XML documentation says is an interface:

enter image description here

How is it possible, has visual studio confused it with something else? Or what allows this interface to be instantiated?

Jonathan Nixon
  • 4,940
  • 5
  • 39
  • 53
JAX
  • 1,540
  • 3
  • 15
  • 32

2 Answers2

14

It's because it's a COM interface. COM interfaces - and only COM interfaces - can be instantiated directly. The runtime will create an instance of the real type behind the scenes. Personally I think it's a bit ugly (and I can't find any references to it in the C# spec) but there we go.

You can actually fake this so that the C# compiler will believe your interface is a COM type without getting COM involved properly... see my related question for details.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

You can't instantiate an interface in c# by definition and Application is not a regular .NET interface, but a COM interface. From MSDN:

This is a .NET interface derived from a COM coclass that is required by managed code for interoperability with the corresponding COM object.

Now, you're probably asking your self how come?

well, when the C# compiler identifies that a System.Runtime.InteropServices.CoClass attribute is decorating a interface, it would automatically use Activator.CreateInstance on the provided type from the CoClass property, for example:

[System.Runtime.InteropServices.CoClass(typeof(Test))] - So a new instance of Test will be created.

Yair Nevet
  • 12,725
  • 14
  • 66
  • 108