Introduction
Hi All , Today we are going to discuss about a most interesting topic which is introduced in c# 4.0(.net framework 4.5). It is used when the type can not be identify at compile-time.
Lets Get Started
Type identified for Dynamic at run-time. It can be declared as below.
dynamic val;
We can assign a value to dynamic variable as below.
dynamic val="Abhi";
In the above the compiler do not know the type of value assigned to "val".
See the below code.
dynamic val="Abhi";
dynamic val=123;
In the above dynamic has the special feature of assign different value to a single variable without type casting.
See the below code.
dynamic val="Abhi";
val++;
Can you say the above code through compilation error or not?
Answer is No. There will be no compilation error ,but of-course you will get error while run time.
So till now we understand that if we are using "Dynamic" then we will not encounter any issue error at run time.
Lets go through some experiment and understand "Dynamic in c#" in a better way.
Lets see the below .
Fig-1 |
In the above screenshot the dynamic(val1,val2) is dynamic type even though we can see the value column as int or string type in watch window.
After execution dynamic converted to its actual type.In this case it is Int and String type.see the below screenshot.
Fig-2 |
We can not get Intelligence in case of dynamic unlike int and string,Because compiler do not have any idea at compile time.
See the below screenshot.
Fig-3 |
We can write as below too without compilation error.
Fig-4 |
See the above i incremented val2 even though this is a string. But But build succeed .
When to use it and When not to use it?
When we do not know about the Object or There is a chances to change the variable type then we should go for dynamic other wise we should prefer non-dynamic(static)type like int,string,var etc....
Thanks...............
No comments:
Post a Comment