SIGN UP MEMBER LOGIN:    
ARTICLE

Creation of objects using Late-Binding technique

Posted by Santhosh Veeraraman Articles | Visual C# September 10, 2007
This article will explain how we can create objects in runtime, using late binding technique. Especially for a situation where you will come to know the class name only in runtime.
Reader Level:

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;

    }

}

Login to add your contents and source code to this article
share this article :
post comment
 
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Team Foundation Server Hosting
Become a Sponsor