Dynamic (C# 4.0) & Var in a nutshell.

Posted by mbcrump on Geeks with Blogs See other posts from Geeks with Blogs or by mbcrump
Published on Fri, 07 May 2010 13:02:12 GMT Indexed on 2010/05/11 2:55 UTC
Read the original article Hit count: 241

Filed under:

A Var is static typed - the compiler and runtime know the type. This can be used to save some keystrokes. The following are identical.

Code Snippet
  1. var mike = "var demo";
  2. Console.WriteLine(mike.GetType());  //Returns System.String
  3.  
  4. string mike2 = "string Demo";
  5. Console.WriteLine(mike2.GetType()); //Returns System.String

A dynamic behaves like an object, but with dynamic dispatch. The compiler doesn’t know anything about it at compile time.

Code Snippet
  1. dynamic duo = "dynamic duo";
  2. Console.WriteLine(duo.GetType()); //System.String
  3. //duo.BlowUp(); //A dynamic type does not know if this exist until run-time.
  4. Console.ReadLine();

To further illustrate this point, the dynamic type called “duo” calls a method that does not exist called BlowUp(). As you can see from the screenshot below, the compiler is reporting no errors even though BlowUp() does not exist.

image

The program will compile fine. It will however throw a runtimebinder exception after it hits that line of code in runtime.

Let’s try the same thing with a Var. This time, we get a compiler error that says BlowUp() does not exist. This program will not compile until we add a BlowUp() method. 

image

I hope this helps with your understand of the two. If not, then drop me a line and I’ll be glad to answer it.

© Geeks with Blogs or respective owner