Dynamic Keyword
In C# 4.0 dynamic keyword was introduced, the advantage of dynamic keyword is that the actual type of variable of dynamic type is decided at run time. You can initialize the variable of dynamic type with any type of value or even if you do not initialize the value then also it will not give any error.
You can also change the value of a dynamic variable to any other type, e.g. if you assign a integer value to a dynamic variable at the time of initialization then later you can also change it to string type of value and you will not get any error.
Let us look at an example of dynamic type of variable below.
As you can see in the above example we have declared a dynamic type variable a and we have not initialized the variable, then we assigned the integer value to it and then later assigned a string type of value, when we build the code we did not get any error and the build has been succeeded.
Dynamic keyword is very useful when working with LINQ queries as we can store the output of the LINQ query in the dynamic keyword.
Difference Between dynamic Keyword and var Keyword .
Dynamic
|
Var |
dynamic is a
dynamically typed variable. |
var is a statically
typed variable. |
dynamic typed
variable is not mandatory to initialize at the time of declaration. |
You need to
assign a value to var type of variable at the time of declaration else you
will get a compile time error. |
You can also
change the value of dynamic variable to any other type other than the type of
value which was assigned before. |
You cannot
assign the value of any other type to var variable other than the type of
value which was assigned when it was initialized else you will get a compile
time error. |
You can use
dynamic type as a method return type and as a type of parameter passed to a
method. |
You cannot
use var type of variable as a method return type or parameter passed to a
method. |
dynamic keyword was introduced in C# 4.0.
|
var keyword
was introduced in C# 3.0. |
So we have looked in this article how we can use dynamic keyword in C#, and also the difference between dynamic and var keyword, I hope you find this article useful.
For more information on C#, .NET please read my other articles.
If you have any queries related to C#, .NET or to provide any feedback, please write a mail on prson94@gmail.com and I will try to get back to you as soon as possible.
If you like the article then please write it in the comments box as it will motivate me to write more articles.
Thank You...….