For training related to .net,OOPS,design patterns, MVC,WCF and .net fundamentals
contact at sukeshmarla@gmail.com or Click Here

14 May 2011

var vs dynamic


    • In case of var type is decided at compile time by compiler=>Complie time Type Interference.
    • As per MSDN,-
               var is a strongly implicitly typed local variable for which the compiler is able to determine the type from the initialization expression.
    • Introduced in 3.5

    • In case of dynamic type is decided at runtime=>Run time Type Interference.
    • As per MSDN,-         dynamic lookup allows you to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the normal static binding of C# and instead gets resolved dynamically.
    • Introduced in 4.0
Example:-
string MyString="Sukesh Marla";
var MyVarVariable=MyString;
Response.Write(MyVarVariable.MyMethod());
when we run the above code,we get a error  'string does not contain a definition for 'MyMethod' and no extension method 'MyMethod' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?
means var knows that what is assgned to it.
string MyString="Sukesh Marla";
dynamic MyVarVariable=MyString;
Response.Write(MyVarVariable.MeMethod());
this will get complied.

and throws exception at runtime,if you wont define any extension method MyMethod for string class.