Accessing a COM component

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.

You might also like...

Comments

About the author

Imtiaz Alam United States

Imtiaz Alam is a Senior Developer, currently residing in Phoenix, Arizona. He has more than five years of development experience in developing Mirosoft based Solution.

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“In theory, theory and practice are the same. In practice, they're not.”