tags:

views:

125

answers:

1

I've seen this quite a few times while using Office Interop classes

this.CustomXMLParts.Add(MyResources.Data, new Office.CustomXMLSchemaCollection());

If I hover over the CustomXMLSchemaCollection class, it shows up as an interface. Then how come I can do a new on it ? What gives? BTW this code compiles and works.

+2  A: 

You are not creating an instance of the CustomXMLSchemaCollection interface but an instance of the CustomXMLSchemaCollectionClass coclass.

The definition for CustomXMLSchemaCollection interface is:

[Guid("000CDB02-0000-0000-C000-000000000046")]
[CoClass(typeof(CustomXMLSchemaCollectionClass))]
public interface CustomXMLSchemaCollection : _CustomXMLSchemaCollection
{
}

This means that the designated coclass that implements the interface is CustomXMLSchemaCollectionClass. My guess is that when the C# compiler sees the new for CustomXMLSchemaCollection interface it translates it to create a COM instance of the CustomXMLSchemaCollectionClass based on the attributes provided with the interface.

After writing this simple example:

namespace ConsoleApplication2
{
    using System;
    using Office = Microsoft.Office.Core;

    class Program
    {
        static void Main(string[] args)
        {
            Office.CustomXMLSchemaCollection test = new Office.CustomXMLSchemaCollection();
        }
    }
}

I just ran ildasm and get the following MSIL:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       8 (0x8)
  .maxstack  1
  .locals init ([0] class [Interop.Microsoft.Office.Core]Microsoft.Office.Core.CustomXMLSchemaCollection test)
  IL_0000:  nop
  IL_0001:  newobj     instance void [Interop.Microsoft.Office.Core]Microsoft.Office.Core.CustomXMLSchemaCollectionClass::.ctor()
  IL_0006:  stloc.0
  IL_0007:  ret
} // end of method Program::Main

As you can see the class that is constructed is CustomXMLSchemaCollectionClass to prove my initial assumption.

smink
OK COM Magic at work again. - Seems like the CoClass Attribute is the key to this off-the-trodden-path behavior. thx
Gishu