Creation of objects using Late-Binding technique


This article will explain how we can create objects in runtime, using late binding technique.

 

Late-Binding

 

Assume you are in a situation where you want to create object of a class only in runtime. Say for example, the class name is known to you only when you read it from an xml configuration file.

 

We can't instantiate it, because of the fact that we do not know which class has to be used. Late-binding technique will give you a hand in such kind of difficult situation.

 

Factory Method

 

We are using a factory method in this example, which will do the job for us. It will get the class name as parameter, create the object and give it back to you.

 

Code:

 

using System;

using EtchingFormExceptions;

 

/// <summary>

/// Factory Class

/// </summary>

public static class Factory

{

    // This is a factory method that returns the required object

    // using late binding.(i.e. the class is available only in runtime)

    public static Employee GetEmployee(string Classname)

    {

        Employee EmployeeObject;

        try

        {

            // Set this as a rule. You have to pass Namespace.Classname

            string FullName = "MyProjectNameSpace." + Classname;

            Type t = Type.GetType(FullName);

 

            // Create instance using Activator class.

            object oTObject = Activator.CreateInstance(t);

           

            // Type cast it to our employee.

            EmployeeObject = (Employee)oTObject;

        }

        catch (Exception)

        {

            throw new ClassNotFoundException();

        }

        return EmployeeObject;

    }

}

Up Next
    Ebook Download
    View all
    Learn
    View all