COM components can be consumed in .NET clients using late binding. To instantiate COM objects using late binding, you must use a two-step process.
First, you must get a type instance. This can be done in one of the following three ways:
Type X = Type.GetTypeFromProgID(Program ID);
Type X = Type.GetTypeFromCLSID(new Guid"Guid Number")
Type X = Type.GetType("string");
Next, create the object, as follows:
Object MyObject = Activator.CreateInstance(X)
The following example demonstrates how COM components can be consumed in .NET clients using late binding.
using System;
using System.Reflection;
namespace Client.Chapter_10___COM_and_.NET_Interoperability
{
class LateBinding
{
[STAThread]
static void Main(string[] args)
{
//Late binding example
Type t = Type.GetTypeFromProgID("SAPI.SpVoice");
//Creates an object
Object o = Activator.CreateInstance(t);
Object[] a = new Object[2];
a[0] = "Hello World";
a[1] = 0;
//Calls a method
t.InvokeMember("Speak", BindingFlags.InvokeMethod, null, o, a);
}
}
}