Monday, 30 January 2017

LATE BINDING USING REFLECTIONS IN C#

EARLY V/S LATE BINDING IN C#

Difference between early and late binding:


1.Early binding can flag errors at compile time. With late binding there is a risk of run time exceptions.

2. Early binding is much better for performance and should always be preferred over late binding. Use late binding only when working with an objects that are not available at compile time.

3. I think 95% of people use early binding over late binding because of late binding is going to be compiled properly at compile time but it will through exception at Runtime "if there is any errors", so early binding is better as it warns the programmer with "wiggly sign" at compile time itself, it does not allow to compile the program.



using System;
using System.Reflection;

namespace ConsoleApplication4
{
    public class MainClass
    {
        private static void Main()
        {
// LATE BINDING STARTS HERE
            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            Type customerType = executingAssembly.GetType("ConsoleApplication4.Customer");


            object customerInstance = Activator.CreateInstance(customerType);


          MethodInfo getFullNameMethod =  customerType.GetMethod("GetFullName");


          string[] parameters = new string[2];

          parameters[0] = "Malla";
          parameters[1] = "Tech";

         string fullName = (string)getFullNameMethod.Invoke(customerInstance, parameters);

         Console.WriteLine("Full Name = {0}", fullName);
         Console.ReadLine();

// LATE BINDING ENDS HERE.

            ///     Early Binding 
        //    Customer C1 = new Customer();
        //    string fullname = C1.GetFullName("Malla", "Tech");
        //    Console.WriteLine("Full Name = {0}", fullname);
        //    Console.ReadLine();
        }
    }


    public class Customer
    {
        public string GetFullName(string FirstName, string LastName)
        {
            return FirstName + " " + LastName;
        }

    }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.