Dynamic type with Reflection in debug mode


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”});


 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.



By running in debug mode, we can see at compile time class is resolving as DynamicReflection.Student.

  1. In 2nd line of code we are finding, type using GetType method of object class.

We can see Compiler is resolving the type as Student. If you remember Student is name of our class.

  1. 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.
  2. Since method of the class is returning void so res is NULL.



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 “);

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.

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.


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

One response to “Dynamic type with Reflection in debug mode”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com