Search code examples
c#comcom-interop

C# call a method from an interface with no defining code


Alright, so I'm new to C# Interfaces. From my understanding, an interface contains method prototypes that a class can implement and use. For example:

interface MyInterface {
    public void printhelloworld();
}

class MyExampleClass : MyInterface {
    public void exampleMethod() {
        printhelloworld();
    }

    public void printhelloworld() {
        System.Console.WriteLine("Hello, world!");
    }
}

However, the Interface I'm having trouble with is in Shell32. More specifically, I'm trying to call the ParseName method of Folder and, from there, the InvokeVerb method of FolderItem.

From what I'm seeing in the Class View, Shell32 has declarations for:

  • An Interface, Folder
  • Another Interface, FolderItem
  • A class, ShellFolderItemClass, that cannot be inherited from

My goal is to invoke a right-click verb on certain directories. However, from what I'm seeing, interfaces require an implementation, meaning that I can't just simply "call the method." The method isn't defined.

How would I make that work?


Solution

  • COM interfaces work differently than normal C# types. Casting a COM instance to an interface invokes QueryInterface. This is CLR magic.

    That's why you can make interface casts work on COM types that statically shouldn't work. Also, casts can fail that normally wouldn't fail.

    I have no experience with the Shell COM API but theoretically (MyInterface)(new MyExampleClass()) can work if all types involved are COM types.