Sunday, March 1, 2015

Dynamic KeyWord in C sharp

It is the new feature introduced in 4.0

A dynamic variable or parameter or field it can have any type. 


Its type can be changed during runtime.


dynamic type variables should be initialized when declared.



Changing type of value assigned to var cannot be changed after assigned to it.

Means , if we assign a int value to var then we cannot assign a string value. this is because on assigning the int value, it will treat as int type thereafter no other type value can assign to it.


Example:



If, i assign a value to integer it wont show any error.



using dynamic keyword




Initially it was assign with integer variable, and again i am reassigning the value to string data type.



output:





Advantages of var keyword

1 We can assign the value to same data type.
var a = 4;
        a = 52;
        Response.Write(a);
2 Intellisense support

Advantages of dynamic keyword.

1 We cannot assign the value to different data type
dynamic a = 9;
        a = "Hi";
        Response.Write(a);
2 No Intellisense support



Example:





output:


We can call any function  or property, if it is not declared also , your code will still compile but you will get runtime exception.





Dynamic types can also be converted explicitly to any other data types 



output:



No comments:

Post a Comment

Thank you for visiting my blog

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...