Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces can't be instantiated but is this an exception [duplicate]

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?

like image 969
JAX Avatar asked May 20 '14 14:05

JAX


People also ask

Can not create instance of abstract class or interface?

No, you cannot create an instance of an abstract class because it does not have a complete implementation. The purpose of an abstract class is to function as a base for subclasses. It acts like a template, or an empty or partially empty structure, you should extend it and build on it before you can use it.

Can an interface throw an exception?

Yes, the abstract methods of an interface can throw an exception.

What is the error you will get when you are trying to create instance of interface?

Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”. In the following example we an interface with name MyInterface and a class with name InterfaceExample.

Is exception in Java a class or interface?

The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java programs.


1 Answers

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.

like image 141
Jon Skeet Avatar answered Oct 22 '22 21:10

Jon Skeet