C# : Early Binding & Late Binding : Part 23
- When we have the information of class and method and we use it to get the value at runtime is called early binding.
- Early binding can throw error during runtime
- Early binding is much more better for performance and should be alwats preferred over late binding.
- In following example the information of class is available and as well as of its type member. It is accessed by using Early binding.
namespace Bindings
{
class Program
{
static void Main(string[] args)
{
//Early Binding
Arithmatic Obj = new Arithmatic();
Obj.NumberOne = 1;
Obj.NumberTwo = 2;
}
}
class Arithmatic
{
public Arithmatic()
{
NumberOne = 0;
NumberTwo = 0;
}
public int NumberOne { get; set; }
public int NumberTwo { get; set; }
public static void addNum(int a, int b)
{
Console.WriteLine(a + b.ToString() + " val");
}
public static void subNum(int a, int b)
{
Console.WriteLine(a + b.ToString() + " val");
}
}
}
Late Binding
- When there is no information of class or method and we use reflection to get the value is called Late Binding.
- In reflection we send class and method / property name to get value
- With late binding there is risk of runtime exception, as it is possible that the class we are trying to access may not be present.
- Late binding is generally preferred when objects are not available during runtime.
- In following example lets assume that the class Arithmatic is not accessible, so reflection is used to get the value from the method in that class
- Note: It is assumed that the class is not accessible but we know all the properties and method present in the class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Bindings
{
class Program
{
static void Main(string[] args)
{
//Late Binding
//loading executing assembly
Assembly execAssem = Assembly.GetExecutingAssembly();
Type ArithmaticType = execAssem.GetType("Bindings.Arithmatic");
//Creating instance of class
object ArithmaticInst = Activator.CreateInstance(ArithmaticType);
MethodInfo getResult = ArithmaticType.GetMethod("addNum");
//Create array and populate it with integers
object[] param = new object[2];
param[0] = 8;
param[1] = 9;
// Invoke the method passing in customerInstance and parameters array
int res = (int)getResult.Invoke(ArithmaticInst, param);
Console.WriteLine("Result is : ", res);
}
}
}
No comments