Late Binding
For Late binding we have to use
System.Reflection namespace, which
allows us to programmaticaly access the types contained in any assembly. We will
see how we can do late bindings in four easy steps..
- We have Get IDispatch Interface using
Type.GetTypeFromProgID("Project1.Class1") - We have to create instance using the type ID
Activator.CreateInstance(objAddType) - We have to make array of arguments (if required)
- Invoke the Method using
objAddType.InvokeMember function.
// Written By ImtiazAlam
using System.Reflection;
using System;
namespace Imtiaz
{
class LateBinding
{
publicstaticvoid Main()
{
//Get IDispatch Interface
Type objAddType = Type.GetTypeFromProgID("Project1.Class1");
//Create Instance
object objAdd = Activator.CreateInstance(objAddType);
//Make Array of Arguments
object[] myArguments = { 100, 200
};
object c;
//Invoke Add Method
c = objAddType.InvokeMember("Add", BindingFlags.InvokeMethod,
null, objAdd, myArguments);
Console.WriteLine(c);
}
}
}
The method Type.GetTypeFromProgID is used to load the type information
of the COM object.The call to Activator.CreateInstance returns an
instance of the COM object. And Finally InvokeMember function is
usedto call the Method of COM object.
Conclusion:
This article gives very basic idea of using the old COM Application, for
the purpose of simplicity and to focus on the purpose of the article no error
handling has been done. In my next article we will see how can we use .NET component
with VB.