Dynamic Type with Reflection in debug mode


Objective

This article will give simple debug mode explanation on how Reflection and Dynamic type works.

Note: Read my previous article on dynamic type here Dynamic Type

Let us create a very simple class called Student.

public  class Student
    {
       public void Print(string Name)
       {
           Console.WriteLine("Student Name is " + Name);
       } 
    }

Now say, you don't have information about type of the class while creating instance of this class. Or in other words you don't have type information of the class at the compile time. So how to create instance of this class? Till c# 3.0 ; we had no choice but to take help of Reflection . Code was highly messy. Not very readable and not beautiful either.

Code will look like,

Object student = new Student();
Type studentType = student.GetType();
 Object res = studentType.InvokeMember("Print", BindingFlags.InvokeMethod,null, student ,new Object[] {"Dhananjay"});
 Console.Read();


Few points about above code

  1. We are creating instance of the Student class as object type. Since we don't know type of the class at compile time.

    Reflection1.gif

    By running in debug mode, we can see at compile time class is resolving as DynamicReflection.Student.
  2. In 2nd line of code we are finding, type using GetType method of object class.

    Reflection2.gif

    We can see Compiler is resolving the type as Student. If you remember Student is name of our class.
     
  3. On the type (StudentType in our case) we are calling the InvokeMember method to call the method on the instance of the class. InvokeMember is overloaded function and we are passing four parameters to this.
     
  4. Since method of the class is returning void so res is NULL.

Output

Reflection3.gif

Now if you see above code, is not it very messy? So in c# 4.0 we do have dynamic type to deal with.

            dynamic dynamicStudent = new Student();
            dynamicStudent.Print("Dhananjay With Dynamimc Type ");
            Console.Read();


Now again if you run the above code in debug mode, you will see type for dynamic type is getting resolved exactly the same as of reflection.
 
Reflection4.gif

After type resolving all the other work to call method is done by compiler at the back ground. So simply we need to call the method on the dynamic type and DLR will take care of everything.

Reflection5.gif

So, we saw in debug mode how dynamic type and reflection works. Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all