The other day I got a task to export some data into excel and the first thing that I looked at was Microsoft.Office.Interop.Excel
library, I don't know that may not be the best way to do that but anyway, what got me in a twist was the fact that I had to make an instance of an interface
. Yeah you can have some object's reference as an interface
if it implements the corresponding one, but I am not talking about that. Basically this is the line of code I am talking about.
Microsoft.Office.Interop.Excel.Application aa = new Microsoft.Office.Interop.Excel.Application();
pretty much this is just a regular object instantiation and there would be nothing special about this if Microsoft.Office.Interop.Excel.Application
was not an interface
. Now, first thing what you learn about interfaces when you are still in your early ages of education is that, you cannot make instance of an interface
. but this proves that it's wrong. Well, not exactly, because this is the IL it generates behind it
IL_0001: ldstr "00024500-0000-0000-C000-000000000046"
IL_0006: newobj instance void [mscorlib]System.Guid::.ctor(string)
IL_000b: call class [mscorlib]System.Type [mscorlib]System.Runtime.InteropServices.Marshal::GetTypeFromCLSID(valuetype [mscorlib]System.Guid)
IL_0010: call object [mscorlib]System.Activator::CreateInstance(class [mscorlib]System.Type)
IL_0015: castclass Microsoft.Office.Interop.Excel.Application
Now here, there is nothing that says "make an instance of an interface" (As I guess), so it's doing something behind that interface
constructor. But still my question remains. How is it possible to use that kind of syntax with interface
and why does compiler not complain about it, and can a regular developer make a thing like this ? Any ideas would be appriciated.