Friday, February 24, 2012

dynamic in C#

.NET framework 4.0 has introduced this new type which is dynamic. When we use the type dynamic, compile-time type checking will be bypassed and the type checking will be resolved at run time. I will explain it with a simple example. Let's take the following code.

     class Program
          static void Main(string[] args)
               dynamic t = new TestClass();

     public class TestClass
          public void TestMethod()

Now if I build the solution, it will be successfully build. In my Main method, I have created an object of 'TestClass' and it's type is dynamic. Now here comes one of the nice thing.

dynamic I

When I try to call the 'TestMethod', intellisense will show me "This operation will be resolved at run time". It's of course because I have used dynamic. Look at the following image.

dynamic II

As you can see here I have called two methods. One is 'TestMethod' which is defined in 'TestClass' and the other is 'Test' which is not defined. The other nice thing is when I run the above program it will successfully compiled and will print "Dynamic". And just after control leaving the first ReadLine only it will throw the error.

dynamic III

So the point is, it will only throw you the error in the run time and not in the compile time.

I can write the same using var type. But when using var, the compiler determines the type in compile time. So not like using dynamic, intellisense will show all the available options. And if I use var here instead of dynamic and I try to call the method 'Test', compiler will throw me the error in compile time. So that's something about dynamic.

Happy Coding.


No comments:

Post a Comment