Search code examples
c#c#-4.0dynamic-languages

Does the new 'dynamic' C# 4.0 keyword deprecate the 'var' keyword?


When C# 4.0 comes out and we have the dynamic keyword as described in this excellent presentation by Anders Hejlsberg, (C# is evolving faster than I can keep up.. I didn't have much time to acquaint myself with the var keyword)

Would I still need the var keyword ? Is there anything that var can do.. that dynamic can't?

var x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x

dynamic x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x

Solution

  • No, they're very different.

    var means "infer the type of the variable at compile-time" - but it's still entirely statically bound.

    dynamic means "assume I can do anything I want with this variable" - i.e. the compiler doesn't know what operations are available, and the DLR will work out what the calls really mean at execution time.

    I expect to use dynamic very rarely - only when I truly want dynamic behaviour:

    • var lets you catch typos etc at compile-time
    • statically bound code is always going to run faster than dynamically bound code (even if the difference becomes reasonably small)
    • statically bound code gives more compile-time support beyond just errors: you can find call hierarchies, refactoring will work better, Intellisense is available etc