Thursday, 7 July 2011

what are the differences between dynamic and var keywords in C#


1)var


You must have to initialize var variables at the time of declaration.
The compiler can identify its type at compile time.

2)dynamic

You dont need to initialize dynamic variables.
The compiler would not be able to identify its type at runtime, 

For Eg:
//var v; This is an error. You must have to initialize the variable
 var v = "v";// It is a string type
 //v.Hi(); This will create a compile time error because compiler knows the variable type during compile time. Here Hi() is not belongs to string type objects. So it will rise an error.
 int len = v.Length;//It is ok because string objects do have Length property

dynamic d; // You dont need to initialize the variable
d = "hi";
int Len = d.Hi();//This code compiles fine. But it will through an exception at runtime.
//when this line of code executes compiler comes to know its type and identifies that this object does not have a property called "Hi()".

No comments:

Post a Comment