Difference between Var and Dynamic in c#
Hello friend,Today I will explain about Difference between Var and Dynamic in c# which is as below:
Var | Dynamic |
Introduced in C# 3.0 | Introduced in C# 4.0 |
Statically typed variable, type of variable declared is decided by the compiler at compile time. | Dynamically typed variable, type of variable declared is decided by the compiler at runtime. |
IntelliSense help available, because Compiler know the variable type. | IntelliSense help doesn’t available,because type of variable would be known at runtime only. |
Error caught at compile time. | Error caught at runtime. |
Could not change assigned variable’s type. e.g. var obj=10; will compile obj=”I am a string”; but if we assigned different type to same variable, if will give error at compile time only. |
Could change assigned variable’s type. e.g. dynamic obj=10; will compile obj=”I am a string”; |
Variable must be assigned any value at initialization. e.g. var obj; will give error at compile time only |
It’s not mandatory to assign value to variable at initialization e.g dynamic obj; will compile successfully. |
var variables cannot be used for property or return values from a function. They can only be used as local variable in a function. | dynamic variables can be used to create properties and return values from a function |
Folks you should also refer below articles for better understanding of differences between confusing concepts:
- Difference between & and && ,| and ||
- Top 9 differences between Array and ArrayList in C#
- Difference between Var and Dynamic in c#
- Difference between RegisterClientScriptBlock and RegisterStartupScript asp.net
- Difference between ref and out parameters in C#
- Difference between static and non-static variable in C#
- Difference between Abstraction and Encapsulation in C#
- Difference between Throw and Throw ex in C#
- Difference between Hashtable and Dictionary
- Difference between Nullable<> and ?
- Difference between String and string in C#
- Difference Between WCF and WebAPI
- Difference between Abstract class and Interface in C#