What is the difference between VAR and Dynamic keyword? ( .NET Interview questions with answers)
- By Shiv Prasad Koirala in .Net
- Nov 27th, 2013
- 10364
- 0
In case you are new to .NET Var keyword please first view this .NET interview question video which explains why we need .NET VAR keyword.
Note :- Comparing VAR and Dynamic keyword is like comparing Apples and oranges. Many people confuse VAR with the variant datatype of VB6 and there's where interviewer tries to confuse you. But there is absolute no connection of var c# keyword with variant of VB6.
Var is early binded (statically checked) while dynamic is late binded (dynamically evaluated).
Var keyword looks at your right hand side data and then during compile time it decides the left hand data type.In other words var keyword just saves you typing lot of things.
On the other hand dynamic keyword is for completely different purpose. Dynamic objects are evaluated during runtime. For instance in the below code the "Length" property exists or not is evaluated during runtime.
dynamic z = "Dynamic";
y = z.Length; // Is Length present or not checked during runtime
If for some reason you mistype the "Length" property to "length" (Small "|") you would end up in to a runtime exception as shown in the below figure.
So in short sentence Var does static check while dynamic evaluates and checks during runtime.
Shiv Prasad Koirala
Visit us @ www.questpond.com or call us at 022-66752917... read more