Last post Oct 19, 2016 04:29 PM by deepalgorithm
Oct 19, 2016 01:46 PM|sudip_inn|LINK
i know the difference between var and dynamic keyword and i many time use var keyword in program but never use dynamic because i do not know the exact scenario where one should use dynamic keyword which will give some advantage and also get some advantage
of dynamic keyword. please discuss it with examples. thanks
Oct 19, 2016 04:29 PM|deepalgorithm|LINK
Generally you should avoid using dynamic as it erases many of the benefits of using a type safe language like c#. Read the following on why its bad practice.
"var" is just an implicitly typed local variable. It's really just a coding style. The compiler generates the same for both variants. More specifically, "var" is only necessary when dealing with anonymous types.
A "dynamic" variable can have any type and its type can change during runtime. The downside is that performance suffers and you lose compile-time checking. From MSDN:
The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time.
Generally, I would avoid using dynamic.
Here are the differences (source):
Introduced in C# 3.0
Introduced in C# 4.0
Statically typed – This means the type of variable declared is decided by the compiler at compile time.
Dynamically typed - This means the type of variable declared is decided by the compiler at runtime time.
Need to initialize at the time of declaration.
var str=”I am a string”;
Looking at the value assigned to the variable
, the compiler will treat the variable
No need to initialize at the time of declaration.
str=”I am a string”;
//Works fine and compiles
Errors are caught at compile time.
Since the compiler knows about the type and the methods and properties of the type at the compile time itself
Errors are caught at runtime
Since the compiler comes to about the type and the methods and properties of the type at the run time.
Visual Studio shows intellisense since the type of variable assigned is known to compiler.
Intellisense is not available since the type and its related methods and properties can be known at run time only
will throw a compile error since the variable is not initialized. The compiler needs that this variable should be initialized so that it can infer a type from the value.
var obj1=” I am a string”;
will throw error since the compiler has already decided that the type of obj1 is System.Int32 when the value 1 was assigned to it. Now assigning a string value to it violates the type safety.
will compile and run
dynamic obj1=” I am a string”;
will compile and run since the compiler creates the type for obj1 as System.Int32 and then recreates the type as string when the value “I am a string” was assigned to it.
This code will work fine.