October 10, 2011 07:21 by
Scott
C# 4.0 supports Dynamic Programming by introducing new Dynamic Typed Objects. The type of these objects is resolved at run-time instead of compile-time. A new keyword dynamic is introduced to declare dynamic typed object. The keyword tells the compiler that everything to do with the object, declared as dynamic, should be done dynamically at the run-time using Dynamic Language Runtime(DLR). Remember dynamic keyword is different from var keyword. When we declare an object as var, it is resolved at compile-time whereas in case of dynamic the object type is dynamic and its resolved at run-time. Let’s do some coding to see advantage of Dynamic Typed Objects :)
A year back I wrote a code of setting property of an object using Reflection:
1: Assembly asmLib= Assembly.LoadFile(@"C:\temp\DemoClass\bin\Debug\DemoClass.dll");
2: Type demoClassType = asmLib.GetType("DemoClass.DemoClassLib");
3: object demoClassobj= Activator.CreateInstance(demoClassType);
4: PropertyInfo pInfo= demoClassType.GetProperty("Name");
5: pInfo.SetValue(demoClassobj, "Adil", null);
Notice line 3-5 creates instance of ‘demoClassType’ and set property ‘Name’ to ‘Adil’. Now with C# 4.0 line # 3-5 can be written as simple as:
dynamic dynamicDemoClassObj = Activator.CreateInstance(demoClassType);
dynamicDemoClassObj.Name = "Adil";
Simple isn’t it? Let’s see a slide from Anders Hejlsberg’s session at PDC 2008:
From the above slide, you can call method(s) such as x.ToString(), y.ToLower(), z.Add(1) etc and it will work smoothly :)
This feature is great and provides much flexibility for developers. In this post, we explore the dynamic typed object in C# 4.0. We will explore dynamic in detail and other features as well in the coming posts. Of course there are pros and cons of dynamic programming as well but where C# is going is something like having features of both static languages and dynamic languages.