1

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

CarLibrary ILDASM

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.
Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
hbk
  • 10,908
  • 11
  • 91
  • 124
  • 1
    maybe you want to build an application that you will update on a regular basis... and you don't know what the application will look in the future... – lauCosma Nov 18 '13 at 18:31
  • you mean just add some class (with new part) without rebuilding old version? – hbk Nov 18 '13 at 18:37
  • 1
    If you used interface definitions for your types, you could look at a given assembly and see if it implements the specified interface and dynamically invoke operations on it without explicitly knowing anything about its concrete type (kind of a poor-man's application plugin mechanism). I have used a similar approach to build child screens for a WinForms MDI application in the past. Each screen was self contained in an assembly which implemented an interface. Those assemblies would be dropped into a sub-folder of the application, and I would use reflection and late binding to load them. – codechurn Nov 18 '13 at 18:58
  • so using it i can add some additional function for some programm without doiing all works from "zero", am i correct? – hbk Nov 18 '13 at 19:01

1 Answers1

1

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.

public static IEnumerable<Type> GetSubclassesForType(Type baseClassType)
{
    List<Type> types = new List<Type>();
    foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
    {
       types.AddRange(ass.GetTypes().Where(type => type.IsSubclassOf(baseClassType)));
    }
    return types;
}

public static IEnumerable<Type> GetSubclassesForType(Assembly assembly, Type baseClassType)
{
    return from type in assembly.GetTypes() 
                        where type.IsSubclassOf(baseClassType)    
                        select type;
}

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)

  • so in anyway I must to know whats types and methos are used with (as example) dll for my LateBindings. So it's must be or my dll or i must to use reflection for finding required information about types and method. Also if i understand correctly in any way i must to rebuild full application And for not rebuilding all parts of programm I can kust create new part and build old one with it? – hbk Nov 18 '13 at 18:58
  • 1
    You can always use latebind by loading dlls from a folder,They do not need to have a common interface or be a subclass of something already built. Yes,It is a good practice to have some methods you already know and call, and yes reflection is the most common case for accessing types and their methods in the dll. On your example above you have some common traits in a Car, and have a folder with dlls where you can insert more dlls of children classes in there like a Bus or a bike (Or even compile your dll from a string you may have and load it :D)..Beware loaded dlls cannot be unloaded – Bill Togkas Nov 18 '13 at 20:44
  • Thanks for explanation - currently found step-by-step example - try to code it - got simple WinForms app where i just loaded dll with implemented interface (taht i created). It's work, return required result (MessgageBox), but due to lack of knowlage it's looks like a little bit complicable for me now, so think need to try do something more. – hbk Nov 18 '13 at 20:54