Difference between var and dynamic in C#

CsharpServer Side ProgrammingProgramming

As we know that programming in any language get starts with declaration a variable after which its definition and logic implementation take place. So it is one of the most important factors to know that how to declare variable in any programming language before starts coding in it.

Now if we take an instance of C# language there is change in declaration in variable with the advancement in the language. As in former version of C# all the code written was validated at the compile time itself which made it as Static typed language where variables are getting declared using var keyword. After C#4.0 there is introduction of dynamic where validation of syntax or checking for errors occurs only at run time with this it also introduce keyword dynamic for declaration of variables.

Following are the important differences between var and dynamic.

Sr. No.Keyvardynamic
1Definitionvar is a known as statically typed variable which means that the data type of these variables are inferred at compile time which is done based on the type of value that these variables are initialized with.On other hand dynamic are the dynamically typed variables which clearly implies that their type is inferred at run-time and not the compile time.
2Versionvar in c sharp language is introduced in C#3.0On other hand dynamic is introduced later in C#4.0
3TypeIn case of var the type of variable is identified by compiler at compilation time.On other hand in case of dynamic the type of variable is identified at run time by compiler itself.
4DeclarationIn case of var the variable is initialized at the time of its declaration so that the compiler comes to know the type of variable according to the value assign to it.On other hand in case of dynamic it is not mandatory to be get initialized at the time of declaration.
5ExceptionVariable define with var throws an exception if are not initialized at the time of declaration.While variable define with dynamic do not throw any exception if they are not get initialized at the time of their declaration
Published on 10-Jan-2020 10:42:24