Wednesday, April 8, 2009

Late binding in C#

There are situations where some time it is viable to go for late binding.
though it is a tedious to perform and also needs carefull overall programming.

I was working on a project where clients were continious asking for new changes and want in Auto updates and at that time found late binding better for the situation.

Though early binding is considered as better option than late binding, but late binding has its own benefits. Late bind is most of used for generic object which needs to be known a run time.

in order to illustrate i have created of class library called Calculation which contains Calculate Class. code of that is below:


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

namespace Calculation
{
public class Calculate
{
public Calculate()
{
}

public Int64 Add(Int64 Value1 , Int64 Value2)
{
return Value1 + Value2;
}

public Int64 Multiply(Int64 Value1 , Int64 Value2)
{
return Value1 * Value2;
}
}
}


in order to use this Calculation.dll at run time don't don't make a reference to Calculation.dll. i have placed the dll on the Startup path of my test application.
code for that is listed below:
do not forget to make a reference to System.Reflection

private void button1_Click(object sender , EventArgs e)
{
Assembly assemblyinfo = Assembly.LoadFile(Application.StartupPath+@"\Calculation.dll");
Type[] types = assemblyinfo.GetTypes();

foreach(Type type in types)
{
MethodInfo[] MI = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
object Latebind = Activator.CreateInstance(type);
MessageBox.Show(MI[0].Invoke(Latebind , new object[] { Convert.ToInt64(textBox1.Text),Convert.ToInt64(textBox2.Text)}).ToString());
}
}

here MI[0] referes to Add Method.
you can check the Method order by itterating through MI object