About Interfaces RRS feed

  • Question

  • if it is not allowed to create an instance from abstract class or interface then, how this happens

    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

    Microsoft.Office.Interop.Excel.Application this is an interface and we can create an instance normally, how ??

    Thursday, August 6, 2015 3:19 PM


  • C# has a bunch of COM interoperability stuff built in.  You've stumbled upon one such feature, which is the ability to associate a COM class with an interface and the ability to instantiate it with the syntax you quoted.

    The interface is given a CoClassAttribute, which tells it that this interface represents a class.  That class will also have an attributed Guid, which identifies the CLSID of the COM object to be created.

    This is the metadata for the interface:  (e.g.)

    namespace Microsoft.Office.Interop.Excel
        [CoClass( typeof( ApplicationClass ) )]
        [Guid( "000208D5-0000-0000-C000-000000000046" )]
        public interface Application : _Application, AppEvents_Event
        [ClassInterface( 0 )]
        [ComSourceInterfaces( "Microsoft.Office.Interop.Excel.AppEvents" )]
        [Guid( "00024500-0000-0000-C000-000000000046" )]
        [TypeLibType( 2 )]
        public class ApplicationClass : _Application, Application, AppEvents_Event
            // ... blah blah blah ...

    Now you can say new Microsoft.Office.Interop.Excel.Application and C# knows to create an object with the CLSID specified by the associated CoClass, create an RCW for it, obtain the specified interface etc. ... all the usual COM mojo.  It's all delightfully magical in a we're-doing-what-you-want-behind-the-scenes kind of way.

    Thursday, August 6, 2015 4:05 PM