Wednesday, 12 August 2015

Invoke method dynamicly in C# - Late Binding using Reflection

Late binding is associating a method with an object at runtime.At compile time compiler does not know about this association.

Reflection is one of the way to achieve late binding.

In following example we will inspect the assembly, create object of class at runtime, find method of this class using reflection and call this method using created object.

namespace TypeCastingRND
{  
    public class Program
    {
        public static void Main()
        {
             // Get current Assembly
            Assembly executedAssembly = Assembly.GetExecutingAssembly();          
            Type studentType = executedAssembly.GetType("TypeCastingRND.Student");

           // Create instance of Student class
           object studentInstance = Activator.CreateInstance(studentType);

            // Get method using reflection
            MethodInfo methodName = studentType.GetMethod("StudentFullName");

            //Create parameter array
            string[] parameters = new string[2];
            parameters[0] = "Rahul";
            parameters[1] = "Saini";

            //Invoke method and get return 
            string StudentName=(string)methodName.Invoke(studentInstance, parameters);
            Console.WriteLine("Student Name : " + StudentName);

            Console.Read();
        }
    }

    public class Student
    {
        public string studenFirstName { get; set; }
        public string studenLastName { get; set; }
        public Student()
        {
       
        }
        public string StudentFullName(string FirstName,string LastName)
        {
            return FirstName + " " + LastName;
        }
    }  
}

Output :
Student  : Rahul Saini

No comments:

Post a Comment