65.9K
CodeProject is changing. Read more.
Home

Understanding Dynamic Keyword Using Simple Examples

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Jan 2, 2015

CPOL

4 min read

viewsIcon

11334

Introduction to dynamic keyword for beginners

Let us first have quick look on object and var keywords. If not beginner you can skip object and var section and can directly go to dynamic section.

object

Object is root for all data types and any type of data can be assigned to it.

     object obj; 
     obj = 10;
     obj = 5.5; 
     obj = "mystring";

Here, before assigning any value to obj compiler will first typecast it to object type. For example, in the above code “10” will not be treated as integer and will get converted to object type. Same holds true about “5.5” and “mystring”.

var

     var j = 2;

var variable has to be initialized at the time of declaration. Compiler identifies datatype of right hand side value and declares variable of same type at compile time (type inference). So in the above example, compiler will declare j as integer, i.e., IL (Intermediate Language) will still have the same code as if it is declared as int j = 2.

Note that as var j = 2 is the same as int j = 2 so you can’t assign any other type of data to j in scope, i.e., the following code will not get compiled:

     var j = 2;
     j = 5.5      (Error: Cannot implicitly convert type 'double' to 'int')

var keyword plays a very important role in LINQ queries, especially when query returns collection of anonymous types using projection.

dynamic

dynamic type bypasses static type checking and it gets resolved at runtime. You can assign any value to dynamic type. (You can assign any type of value to object also but in that case value actually gets converted to object type whereas in case of dynamic it will not get converted to object type).

Compiler or IL doesn’t have any knowledge about data assigned to dynamic type. That’s why while using dynamic types, you will not get intellisense support.

You can assign and reassign any type of data to dynamic variable in scope. Try out the following code.

     dynamic i;
     i = 1;
     Console.WriteLine(i.GetType());
     i = "C#";
     Console.WriteLine(i.GetType());
     i = 5.5;
     Console.WriteLine(i.GetType());

You can observe that while typing GetType(), you are not getting intellisense support. If you will try typing the same code just by replacing dynamic with object type, you will get intellisense support (check typing GetType()). Output will be the same in both the cases but in case of dynamic compiler will not have any knowledge about type at compile time.

To understand the difference between object and dynamic, try out the following example.

Create class Student:

     public class Student
     {
        public string FirstName { get; set; }
        //few more properties....
        
        public void CalculateResult()
        {
            //code
        }
     }

In Main, type the following code (please do not copy paste for better understanding):

     //using object
     object s1 = new Student();
     ((Student)s1).FirstName = "Anand";
     ((Student)s1).CalculateResult();

     //using dynamic
     dynamic s2 = new Student();
     s2.FirstName = "Albert";
     s2.CalculateResult();

When using Object type to declare reference; Student object is getting implicitly typecasted into object type. So to access Student properties and methods, you have to again type-cast it back to Student type. Also note that while typing code you are getting intellisense support (as compiler (and Visual Studio) will have knowledge about datatype of s1).

In case of dynamic, compiler will not have any knowledge about type. At compile time, s2 is neither of object type nor of student type. That’s why while typing code, you will not get intellisense support and you have to manually type property and method names. But as we are assigning Student object to s2, it will get declared as Student type at runtime. So here we need not to type-cast it.

To understand it one level up, type the following code:

     //using object
     object s1 = new Student();
     ((Student)s1).Firstname = "Anand";
     ((Student)s1).CalculateResult();

     //using dynamic
     dynamic s2 = new Student();
     s2.FirstName = "Albert";
     s2.CalculateResult();

In the above code, we are intentionally making a mistake while typing FirstName property for s1. Now if you will compile code, compiler will not allow you to compile. As compiler knows s1 is of Student type and there is no Firstname property that exists in that class.

Now try the following:

     //using object
     object s1 = new Student();
     ((Student)s1).FirstName = "Anand";
     ((Student)s1).CalculateResult();

     //using dynamic
     dynamic s2 = new Student();
     s2.Firstname = "Albert";
     s2.CalculateResult();

Here, we are making the same mistake for s2 but surprisingly program will get compiled successfully, as compiler doesn’t have any idea about of what type s2 will be. Yes you are right, you will definitely get an error at runtime as there is no such property that exists in Student class.

In short, compiler will simply not bother about dynamic types. As the name suggests, they will get resolved at runtime. (While typing, you need to be careful as intelligence support is not there.)

What you can do using dynamic keyword, you can do without using it. But in case of reflection and COM programming, dynamic keyword reduces your typing efforts and simplifies source code drastically!

To realize the greatness of dynamic keyword, let us try out a simple reflection example.

Create class Employee as follows:

     class Employee
     {
        public string Name { get; set; }
        public string Designation { get; set; }

        public void PrintDetails()
        {
            Console.WriteLine("{0}, {1}",Name, Designation);
        }
     }

Not to do reflection over Employee class, either you can write code without using dynamic keyword:

     static void Main(string[] args)
     {
         //without using dynamic keyword
         //to get Employee type
         Type t = typeof(Employee);

         //to create object of Employee type
         object empObj = Activator.CreateInstance(t);

         PropertyInfo prop;

         //to get "Name" property info 
         prop = t.GetProperty("Name");
         //to set value to "Name" property
            prop.SetValue(empObj, "Sachin", null);

         //to get "Designation" property info
         prop = t.GetProperty("Designation");
         //to set value to "Designation" property
         prop.SetValue(empObj, "Cricketer", null);

         //to invoke/call "PrintDetails" method
         t.InvokeMember("PrintDetails", BindingFlags.InvokeMethod | 
        BindingFlags.Instance | BindingFlags.Public, null, empObj, null);

         Console.ReadKey();
     }

Or you can oversimplify it using dynamic keyword!!!

     static void Main(string[] args)
     {
         //with using dynamic keyword
         //to get Employee type
         Type t = typeof(Employee);

         //to create object of Employee type
         dynamic d = Activator.CreateInstance(t); 

         //to set values to property
         d.Name = "Sachin";
         d.Designation = "Cricketer";

         //to invoke/call "PrintDetails" method
         d.PrintDetails();

         Console.ReadKey();
     }

I hope this is enough to convince you about the greatness of dynamic keyword especially when working with reflection. If not, you can always Google for few more examples:)