Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Understanding Late binding

, 28 Apr 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
in simplest words, late binding is a technique, in which you can create an instance of a given type, and can invoke its methods, at runtime, without having knowledge of its existence at the compile time. System.Activator class plays a pivotal role in late binding process. let us understand, it by cr

in simplest words, late binding is a technique, in which you can create an instance of a given type, and can invoke its methods, at runtime, without having knowledge of its existence at the compile time.

System.Activator class plays a pivotal role in late binding process.

let us understand, it by creating

  • simple a Class library “MyMathLib” which exposes few methods let say Add, Subtract, Multiply.
  • Console bases client program , that will use this library using the conventional (early binding) method.
  • Console bases client program , that will use this library using the late binding method.

Creating the class library

Create a Class library, let’s name it “MyMathLib” choosing the “Class Library” template from the project wizard. Default project is created with a public class Class1 defined in Class1.cs.

Little house keeping.

rename the Class1 as “MathClass” using the refactor menu.

rename the class1.cs as MathClass.cs

Now define methods Add, Subtract and Multiply for MathClass as shown below.  as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyMathLib
{
    public class MathClass
    {
        public double Add(double dblX, double dblY)
        {
            return (dblX + dblY);
        }

        public double Subtract(double dblX, double dblY)
        {
            return (dblX – dblY);
        }

        public double Multiply(double dblX, double dblY)
        {
            return (dblX * dblY);
        }
    }
}

 

Compile and Build library.

Creating the Application, that will use this library

Create a Console application, let’s name it “TestEarlyBinding” choosing the “Console Application” template from the project wizard. Default project is created.

Little house keeping.

Add Reference of MathLib class library project, created earlier.

Write code in the main function to use this library as shown below.

using System;
using System.Text;

using MyMathLib;

namespace TestEarlyBinding
{
    class Program
    {
        static void Main(string[] args)
        {
            double dblResult = 0;
            double dblX = 200; double dblY = 200;
           
            Console.WriteLine("Tesing early binding");  
           MathClass mathObj = new MyMathLib.MathClass ();
           
            dblResult = mathObj.Add(dblX, dblY);
            Console.WriteLine("Adding {0} and {1} results to {2}", dblX, dblY, dblResult);

            dblResult = mathObj.Subtract (dblX, dblY);
            Console.WriteLine("Adding {0} and {1} results to {2}", dblX, dblY, dblResult);
           
            dblResult = mathObj.Multiply(dblX, dblY);
            Console.WriteLine("Adding {0} and {1} results to {2}", dblX, dblY, dblResult);
        }
    }
}

Compile and build and here is the output.

image

till now, it was default way, we used to do things, but this post is about late binding.

so using the same class library  with late binding, let’s create one more console based project let’s  call it TestLateBidning.

using System;
using System.Text;
using System.Reflection;

namespace TestLateBidning
{
    class Program
    {
        static void Main(string[] args)
        {
            double dblResult = 0;
            double dblX = 200; double dblY = 100;

            Console.WriteLine("Tesing late binding");
           
Assembly assem = null;
           
Console.WriteLine("Loading MyMathLib assembly . . .");
            try
            {
                assem = Assembly.Load("MyMathLib");
            }
            catch (Exception eX)
            {
                Console.WriteLine("Error while loading MyMathLib Error [{0}] \n\nMyMathLib.dll not found in application Folder", eX.Message);
                return;
            }

            Console.WriteLine("Creating Instance of MathClass object . . .");
            Type mathType = assem.GetType("MyMathLib.MathClass");
            object mathObjLB = Activator.CreateInstance(mathType);

            Console.WriteLine("Invoke method [Add] . . .");
            MethodInfo miAdd = mathType.GetMethod("Add");
            dblResult = (double)miAdd.Invoke(mathObjLB, new object[] { 100, 200 });
            Console.WriteLine("Adding {0} and {1} results to {2}", dblX, dblY, dblResult);

            Console.WriteLine("Invoke method [Subtract] . . .");
            MethodInfo miSub = mathType.GetMethod("Subtract");
            dblResult = (double)miSub.Invoke(mathObjLB, new object[] { 100, 200 });
            Console.WriteLine("Subtracting {0} and {1} results to {2}", dblX, dblY, dblResult);

            Console.WriteLine("Invoke method [Multiply] . . .");
            MethodInfo miMul = mathType.GetMethod("Multiply");
            dblResult = (double)miMul.Invoke(mathObjLB, new object[] { 100, 200 });
            Console.WriteLine("Multiply {0} and {1} results to {2}", dblX, dblY, dblResult);
        }
    }
}

Explanation:

Assembly assem = null;
Console.WriteLine("Loading MyMathLib assembly . . .");
try
{
    assem = Assembly.Load("MyMathLib");
}
catch (Exception eX)
{

    . . . . .    
    return

}

Assembly class represents an assembly, which is a valid building block of a common language runtime.

Load method simply loads an assembly, whose name has been provided.

Type mathType = assem.GetType("MyMathLib.MathClass");
object mathObjLB = Activator.CreateInstance(mathType);

Activator class contains methods to create types of object of the specified type, locally or remotely. 

MethodInfo miAdd = mathType.GetMethod("Add");

GetMethod is member function of Type class, that searches the given method name, and returns the MethodInfo, MethodInfo class discovers the attributes of a method access its metadata.

dblResult = (double)miAdd.Invoke(mathObjLB, new object[] { 100, 200 });(mathObjLB, new object[] { 100, 200 });

Invoke method of MethodInfo class simply calls the method, using the required parameters.

similarly other methods (Subtract, Multiply) are discovered and invoked.

build and execute.

image

oops, there was an error, as it could not found the MyMathLib.dll in the test application executable (TestLateBinding.exe) folder.

just copy the MyMathLib.dll to the test application’s executable folder and execute the client again. and you will see what was expected.

image

 

Hope it useful.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Praveen Kumar Katiyar
Founder BriskTech Solution
India India
More than 10 years of experience in designing and development of GUIs and Middleware for industrial control systems.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150327.1 | Last Updated 28 Apr 2014
Article Copyright 2014 by Praveen Kumar Katiyar
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid