By Yuvaraj Shanmugam

Dynamic Vs Var in C#

Using the dynamic keyword vs the var keyword can be confusing. In this post I am going to explain the differences between dynamic and var keywords.

dynamic – is just an object which does not require any initialization

var – is a datatype that is inferred during compile time, which means you cannot create a variable without assigning an initial value.

The above example code shows error highlight for var which does not have initialization.

A dynamic object can change type after being assigned but var cannot change type after assigned.

The above example shows that testDynamic initially having assigned to integer will be converted to float when added with a float number. This is not possible with testVar and it will throw error if we try to add with different type.

A dynamic object can be used as a return value for a function but var cannot be used to return value in a function

I hope you had found this post useful. Please do post your comments.

Leave a Reply

Your email address will not be published. Required fields are marked *