27-May-2010
What is it?As we all know C# is a strongly typed language, and as we also know late binding 99.99% of the time is a really bad idea (performance and maintainability). To a certain extent the dynamic keyword is a step away from a strongly typed variable type. So what is the new dynamic keyword? Lets have a look at an example:
The above code compiles and runs producing the following output. Things to note:
Basically the dynamic keyword bypasses all of C#'s type checking.You will still get exceptions at runtime to show inappropriate operations. Consider this.... namespace DynamicKeyword { using System; public class Program { public static void Main(string[] args) { Console.WriteLine("Test1"); dynamic variant = 123.44; Console.WriteLine(variant.Foo()); // Will compile but not work } } } Output at runtime: So type checking goes out the window. Sounds like an extremely dangerous tool to make your fellow developers go nuts debugging your carefully job-secured code. Why is this potentially useful while making a mockery of strongly typed code?
What is the difference between var and dynamic?Easy. Var is strongly typed dynamic is not. Dynamic bypasses all of C#'s type checks at intelli-sense-time and at compile time. Var simple is a macro for the compiler to insert the appropriate type name at compile time. The type is inferred from the right hand side of the assignment (=) operator. Var makes code far easier to refactor and saves you typing. If you want to know the type simply hover the mouse over the var keyword it will tell you. namespace DynamicKeyword { using System; public class Program { public static void Main(string[] args) { Console.WriteLine("Test1"); dynamic variant = "hello world"; Console.WriteLine(variant); Console.WriteLine(" of type " + variant.GetType().Name); variant = 123.44; Console.WriteLine(variant); Console.WriteLine(" of type " + variant.GetType().Name); Console.WriteLine("Test2"); var notVariant = "Hello World Again!"; Console.WriteLine(notVariant); notVariant = 123.45; // Does not compile } } } ![]() Resistance is futile. |