Currently I'm try to understand some of aspects regarding programming in C#. Now I'm learning LateBinding
. I understand how to create some simple program like the one below.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Try to do something with late bindings");
Assembly a = null;
try
{
a = Assembly.Load("CarLibrary");
Console.WriteLine("1");
}
catch (FileNotFoundException ex)
{
Console.WriteLine(ex.Message);
}
if (a == null)
{
CreateUsingLateBinding(a);
}
Console.ReadLine();
}
private static void CreateUsingLateBinding(Assembly asm)
{
try
{
Type sportCar = asm.GetType("CarLibrary.SportCar");
object obj = Activator.CreateInstance(sportCar);
Console.WriteLine("Success");
MethodInfo mi = sportCar.GetMethod("TurboBust");
mi.Invoke(obj, null);
}
catch (Exception)
{ }
}
I also created CarLibrary.dll and put it in one folder. ILDASM screenshot
All works fine. I just have a few questions regarding this topic
- When it's usefull to use this?
- If I use LateBinding is it supposed that I don't know anything about resource that I want to use or I know everything about it (in this case why I just can't write program in normal way, if I know every class and method from this resource)? It's still a little bit confusing to me - try to find answer - result only how to use.
Well, imagine that you have some child classes
ex Dll A
public class Student : Person { }
Dll B
public class Teacher : Person { }
The Person can be in a common assembly referenced by these dlls and your application, having thus different implementations of a virtual method etc. Using reflection you can load all the classes that inherit from the class Person.
Another use of Late Binding is that it can be used if you want to update your application by only copying the dll that contains some part of your code. This can really help when you want update fast multiple client applications.(Note: you should also cache the results of the reflection after the Late Binding to increase performance)