locked
FAQ Item: What are the differences between the keyword var and dynamic? RRS feed

  • Question

  • What are the differences between the keyword var and dynamic?
    Sunday, June 20, 2010 11:49 AM

Answers

  • Q: What are the differences between the keyword var and dynamic?

    A: Dynamic and var represent two completely different ideas.

    var:

    var essentially asks the compiler to figure out the type of the variable based on the expression on the right hand side of the assignment statement. The variable is then treated exactly as if it were explicitly declared as the type of the expression. For example the following two statements are equivalent

    var a = "foo";

    string a = "foo";

    The key to take away here is that "var" is 100% type safe and is a compile time operation.

    http://msdn.microsoft.com/en-us/library/bb383973.aspx

     

    dynamic:

    Dynamic is in many ways the exact opposite of var. Using dynamic is essentially eliminating all type safety for that particular variable. It many ways it has no type. When you call a method or field on the variable, the determination on how to invoke that field occurs at runtime. For example

    dynamic d = SomeOperation();

    d.Foo(); // Will this fail or not?  Won't know until you run the program

    The key to take away here is that "dynamic" is not type safe and is a runtime operation.

    http://msdn.microsoft.com/en-us/library/dd264736.aspx

     

    Related threads:

    http://stackoverflow.com/questions/298277/does-the-new-dynamic-c-4-0-keyword-deprecate-the-var-keyword

     

    For more FAQ about Visual C# General, please see Visual C# General FAQ

    • Marked as answer by MSDN FAQ Sunday, June 20, 2010 11:51 AM
    Sunday, June 20, 2010 11:50 AM