Dynamic (C# 4.0) & Var in a nutshell.
- by mbcrump
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 var mike = "var demo"; Console.WriteLine(mike.GetType()); //Returns System.String string mike2 = "string Demo"; 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 dynamic duo = "dynamic duo"; Console.WriteLine(duo.GetType()); //System.String //duo.BlowUp(); //A dynamic type does not know if this exist until run-time. 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. 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. 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.