PRB: Using Reflection Without the Meta Data Permits Only Methods on the Default IDispatch Interface to Be Invoked (318664)



The information in this article applies to:

  • Microsoft .NET Framework 1.1
  • Microsoft .NET Framework 1.0

This article was previously published under Q318664

SYMPTOMS

When you create a COM component in a late-bound fashion by using reflection without the meta data, the client can only invoke methods and properties on the default IDispatch interface.

RESOLUTION

To work around this problem, use the following code:
using System;
using System.Runtime.InteropServices;

namespace SampleApplication
{
	//The COM Server in this example is MyComCoClass, which implements a non-default
	//interface, IDerivedFromIDispatch, which is derived from IDispatch.

	// Declare IDerivedFromIDispatch as a COM interface that 
	// derives from IDispatch interface:
	[Guid("25C5B012-A7F1-4E2E-8AD8-363B31D27DE4"), 
	InterfaceType(ComInterfaceType.InterfaceIsDual)] 
	interface IDerivedFromIDispatch   // You cannot list any base interfaces here. 
	{ 
		// Note that IUnknown Interface members are NOT listed here:
		void DoStuff();

	}

	// Declare the MyComCoClass COM coclass:
	[ComImport, Guid("3754AFD8-24F4-4A2C-9857-FB990B11A204")] 
	class MyComCoClass 
	{ 
		// You cannot have any members here. 
		// Note that the C# compiler will add a default constructor
		// for you (no parameters).
	}
	
	class Class1
	{
		[STAThread]
		static void Main(string[] args)
		{
			// Create an instance of SampleApplication.
			// (Calls CoCreateInstance(3754AFD8-24F4-4A2C-9857-FB990B11A204, 
			//  NULL, CLSCTX_ALL, IID_IUnknown, 
			//  &oApplication). Returns null on failure.):
			SampleApplication.MyComCoClass oApplication = new SampleApplication.MyComCoClass();
									
			// You need to cast this so C# will know what type of object it really is.  
			SampleApplication.IDerivedFromIDispatch ci = (SampleApplication.IDerivedFromIDispatch) oApplication;

			// Call a method on coClass.
                           // DoStuff accepts no parameters and does not return a value.
			ci.DoStuff();			
		}
	}
}
				

STATUS

This behavior is by design.

MORE INFORMATION

Steps to Reproduce the Behavior

The following code only invokes methods and properties on the default interface.
using System;
using System.Reflection;

namespace SampleApplication
{
	class Class1
	{
		[STAThread]
		static void Main(string[] args)
		{
			Type typ;
			Object obj;
			typ = Type.GetTypeFromProgID("COMComponent.MyComCoClass");
			
			obj = Activator.CreateInstance(typ);
			
			// DoStuff accepts no parameters and does not return a value.	
			typ.InvokeMember("DoStuff",BindingFlags.InvokeMethod,null,obj,null);
		}
	}
}
				

Modification Type:MajorLast Reviewed:4/8/2003
Keywords:kbCOMInterop kbpending kbprb KB318664