Click here to Skip to main content
Click here to Skip to main content

Tagged as

Reflection Concept and Late Binding in C#

, 30 Jun 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Reflection Concept and Late Binding in C#

Introduction

Reflection concept in C# is the ability to inspect metadata of assembly at runtime meaning assembly content is described by looking at the assembly metadata at run time namespace.

When it comes to using reflection in practice scenarios, it is very confusing for the developers to use refection concept properly and get benefit for this beautiful feature.

In this tip, I am trying to explain the Reflection concept and the particle uses in projects.

In simple terms, refecltion is reflection provides objects that encapsulate assemblies, modules and types meaning reflection provides a way for dynamic creation of an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

Reflection

Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. The classes that give access to the metadata of a running program are in System.Reflection.

System.Reflection namespace defines the following types to analyze the module's metadata of an assembly: Assembly, Module, Enum, ParameterInfo, MemberInfo, Type, MethodInfo, ConstructorInfo, FieldInfo, EventInfo, and PropertyInfo.

Reflection provides objects that encapsulate assemblies, modules and types.

Assembly Metadata

I am giving a quick view about an assembly which is a logical DLL or EXE which is described by manifest which is nothing but a detailed description (metadata) of an assembly. The .NET compiler produces a portable executable PE file for CLR with the extensions of .exe or .dll. This PE file is mainly comprised of metadata and IL (Intermediate Language).

Explanation

Whenever a .NET project is built, the code will be get complied into Intermediate language and then packaged in assembly. An assembly contains metadata which has the information about the type of classes defined meaning it contains all the required information about the members, fields, constructors, properties, methods, function, etc. used in the class for building the package.

By using reflection, an assembly can be inspected.

Type _type = Type.GetType("ReflectionConcept.Employee");

Or:

Type _type = typeof(Employee);

Sample Code

namespace ReflectionConcept
{
    public class Employee
    {
        public int empID { get; set; }
        public string empName { get; set; }
        public float Salary { get; set; }

        public Employee()
        {
            this.empID = -1;
            this.empName = string.Empty;
            this.Salary = 0;
        }

        public Employee(int id, string name, float salary)
        {
            this.empID = id;
            this.empName = name;
            this.Salary = salary;
        }

        public void displayName()
        {
            Console.WriteLine("Name :" + this.empName);
        }

        public void printSalary()
        {
            Console.WriteLine("Salary :" + this.Salary);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
           Type _type = Type.GetType("ReflectionConcept.Employee");

           // Type _type = typeof(Employee);

            Console.WriteLine(_type.FullName);
            Console.WriteLine(_type.Namespace);
            Console.WriteLine(_type.Name);

            PropertyInfo[] info  = _type.GetProperties();

            foreach (PropertyInfo propinfo in info)
            {
                Console.WriteLine(propinfo.Name);
            }

            MethodInfo [] methods=_type.GetMethods();

            foreach (MethodInfo methodinfo in methods)
            {
                Console.WriteLine(methodinfo.ReturnType.Name);
                Console.WriteLine(methodinfo.Name);
            }

            Console.ReadLine();
        }
    }
}

Uses of Reflections

A. Reflection is very heavily used by IDE developers or UI designers. Property window in .NET application uses refection to show list of properties.

Still confused… alright let me take an example of web application.

In web application, whenever developers drag and drop a control from control list to form. Here reflection plays the role to provide way to dynamically display all the properties of a label and these properties can be changed as per the requirement. So this concept is very important and useful.

B. Late binding can be achieved by using refection meaning it gives the developer a way to use code that is not available at compile time. By using refection instance of type can be created dynamically which doesn’t have information at compile time.

Important Sticky

  • It allows view attribute information at runtime.
  • It allows examining various types in an assembly and instantiate these types.
  • It allows late binding to methods and properties.
  • It allows creating new types at runtime and then performs some tasks using those types.

Late Binding Using Reflections

Before learning late binding, let us have a look for the early binding.

Early Binding can be explained by the situation where the compiler knows about what kind of objects it is, what all the methods are and the properties it contains.

In the example at compile time, the developer has information about the Employee class and all attributes of the class. So here in early binding, we just need to create an instance of the Employee class and methods, properties with that class can be used easily.

   Employee emp = new Employee();
     emp.displayName();<!--/pre-->

Late binding is nothing but binding at run time. Compiler does not know what kind of object it is, what are all the methods and properties it contains.

Late binding is achieved by using reflections.

Sample Code

namespace ReflectionConcept
{
    public class Employee
    {
        public int empID { get; set; }
        public string empName { get; set; }
        public float Salary { get; set; }

        public Employee()
        {
            this.empID = -1;
            this.empName = string.Empty;
            this.Salary = 0;
        }

        public Employee(int id, string name, float salary)
        {
           this.empID = id;
            this.empName = name;
            this.Salary = salary;
        }

        public void displayName()
        {
            Console.WriteLine("Name :" + this.empName);
        }

        public void displayemp(string name)
        {
            Console.WriteLine("Name :" + name);
        }

        public void printSalary()
        {
            Console.WriteLine("Salary :" + this.Salary);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Assembly exceutable = Assembly.GetExecutingAssembly();
            Type Ltype =exceutable.GetType("ReflectionConcept.Employee");

            object objEmployee = Activator.CreateInstance(Ltype);

            MethodInfo method = Ltype.GetMethod("displayemp");

            string[] parameter = new string[1];

            parameter[0] = "Abhishek";

           string employeeName=   (string)method.Invoke(objEmployee, parameter);

                Console.ReadLine();
        }
    }
}

Early Binding Vs Late Binding

  • Performance will be good in early binding.
  • Application will run faster in Early binding, since no boxing or unboxing is done here but in late binding, we need type conversion as it will be decoded at run time.
  • Easier to write the code in Early binding, since the intelligence will be automatically populated .
  • Less chances of errors in early binding, as syntax is checked which flags error at compile time itself but for late binding there are chances of run time exceptions.
  • Late binding would support in all kind of versions, due to handing at run time.
  • Minimal impact of code in future enhancements, if late binding is used.

Conclusion

Above, we have compared early binding and late binding features and found late binding is complex and need more lines of code, is venerable to run time exceptions, has issues with performance, no intelligence by .NET.

So it is very important to understand where late binding should be used.

Answer would be when we are working with objects that are not available at compile time and so this can be achieved using reflection, but it is recommended to use if you have a scenario in the project where you don’t have required information about the object available at compile time.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Abhishek Geek
Technical Lead
India India
No Biography provided

Comments and Discussions

 
Questionlate binding? PinmemberAaron Sulwer15-Sep-14 9:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 30 Jun 2014
Article Copyright 2014 by Abhishek Geek
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid