Dot Net For All

What is late binding and how to achieve in .NET

Hello friends, In this article I will help you to understand the late binding in programming with code examples in C#. Late binding helps us to achieve extensibility and create instances of the class at run time. And Late binding takes help of Dependency Injection to achieve the functionality.

What is Dependency Injection

To understand and use the late binding we have to first understand the Dependency Injection(DI). DI is used to achieve Dependency Inversion principle. In the example shown in my previous article I have used dependency injection for the method.

What is late binding

To achieve DI we create an abstract class or interface and the instance of this abstract class or interface is kept as parameter for the constructor or the method.

Code Example of Dependency Injection

In this code example I will show you how we can achieve dependency injection to write out the first “Hello World” program everyone loves to write.

As you can see in the below code, I am not simply writing the “Hello World”. Instead I have used dependency injection and created a container interface named IMessageWriter. This interface can be extended to write to any output format.

        private static void Main()
        {
            IMessageWriter writer = new ConsoleMessageWriter();
            var salutation = new Salutation(writer);
            salutation.Exclaim();

            Console.ReadLine();
        }

Lets look at out ConsoleMessageWriter in the below code. This class is used to write the message on the console. Similarly you can write DBMessageWriter, TextMessageWriter or anything else.

 public interface IMessageWriter
    {
        void Write(string message);
    }
  public class ConsoleMessageWriter : IMessageWriter
    {
        public void Write(string message)
        {
            Console.WriteLine(message);
        }
    }

Now comes the implementation of the core engine of our code which processes and writes the message i.e. Salutation class.

public class Salutation
{
    private readonly IMessageWriter writer;

    public Salutation(IMessageWriter writer)
    {
        if (writer == null)
        {
            throw new ArgumentNullException("writer");
        }

        this.writer = writer;
    }

    public void Exclaim()
    {
        this.writer.Write("Hello World");
    }
}

This class takes the IMessageWriter as the parameter. Since the parameter is an interface, the class implementing the parameter can be passed at compile time and rest will be taken care. As you can see the Salutation class has single responsibility of printing the message. There will be no need to change this class if we want to change the message writer.

Now with the above code example we have achieved many benefits. Some of them are listed below. I have mentioned these benefits in brief and I will keep the detailed discussion as future topic.

BenefitDescriptionWhen is it valuable?
Late bindingServices can be swapped with other services.Valuable in standard software, but perhaps less so in enterprise applications where the runtime environment tends to be well-defined
ExtensibilityCode can be extended and reused in ways not explicitly planned for.Always valuable
Parallel developmentCode can be developed in parallel.Valuable in large, complex applications; not so much in small, simple applications
MaintainabilityClasses with clearly defined responsibilities are easier to maintain.Always valuable
TESTABILITYClasses can be unit tested.Only valuable if you unit test (which you really, really should)

What is late binding and how to achieve it

As you can see in the above, if I want to provide a new way to print out the message, I have to pass the implementation of IMessageWriter interface at compile time. The problem with this approach is I have to change and compile the code every time. And hence do one more deployment in the production.

To prevent myself from this scenario, I can use late binding as shown in the code below.

I have to include a key in the App.config file as shown below

<appSettings>
    <add key="messageWriter"
         value="ConsoleApp1.ConsoleMessageWriter,
       ConsoleApp1" />
  </appSettings>

And change me main code as shown below

            var typeName = ConfigurationManager.AppSettings["messageWriter"];
            var type = Type.GetType(typeName, true);
            IMessageWriter writer = (IMessageWriter)Activator.CreateInstance(type);
            var salutation = new Salutation(writer);
            salutation.Exclaim();

The benefit of the above code is that the implementation of the IMessageWriter can be changes at run time without even compiling the solution.

The GetType in the above code takes the AssemblyQualifiedName of the class.

You can find the same by using the below code.

Type t = typeof(ConsoleMessageWriter);
string s = t.AssemblyQualifiedName;

Console.WriteLine("The Assembly qualified assembly name " +  "containing the specified class is {0}.", s);

Conclusion:

In this article I have shown you how to achieve the late binding in .NET project with C# language. I showed you how late binding helps you to achieve dependency injection.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview