Var vs Dynamic
The var keyword
The var keyword was introduced in C# 3.0 and variables declared with var are statically typed. Here, the type of variable declared is decided at the compile time. Variables which are declared as var should be initialized at the time of declaration. By looking at the assigned value, the compiler will decide the variable type. As compiler knows the data type of the variable at compile time, errors will be caught at that time only.
Example
- var obj "c-sharp corner";
- obj = 10;
The dynamic keyword
The dynamic keyword was introduced in C# 4.0 and variables declared with dynamic were dynamically typed. Here, the type of variable declared is decided at runtime. Variables which are declared as dynamic don't need to initialize the time of declaration. The compiler won't know the variable time at the time of compiling; hence errors can't be caught by the compiler while compiling. IntelliSense is not available since the type of variable will be decided at runtime.
The dynamic keyword was introduced in C# 4.0 and variables declared with dynamic were dynamically typed. Here, the type of variable declared is decided at runtime. Variables which are declared as dynamic don't need to initialize the time of declaration. The compiler won't know the variable time at the time of compiling; hence errors can't be caught by the compiler while compiling. IntelliSense is not available since the type of variable will be decided at runtime.
Example
- dynamic obj = "c-sharp corner";
In the above code, obj will be treated as a string.
- obj = 10;
Comments
Post a Comment