In this post, we will understand the main difference between Var and Dynamic Keywords in C#.
Topics Covered
Var and Dynamic Keywords in C#
These keywords are used to declare a variable in C#. We will have a look at each of them with the help of an example.
Var Keyword
Let’s start with knowing the features of Var Keyword in C#:
- It was introduced in C#3.0
- This is statically typed.
- We need to initialize it at the time of the declaration.
- Errors are caught at compile time.
- Intellisense is supported.
- var does not allow the type of value assigned to be changed after it has been assigned.
Var in C# Example:
class Program
{
static void Main(string[] args)
{
var result = 1;
result = "Hi";
Console.WriteLine(result);
Console.ReadLine();
}
}
As per the properties, this code should throw a compile-time error as we are trying to modify the value of the result from integer to string. Let us run the program now and see the output.
As expected we get a compile-time error. Let us remove the second line of code and run the program.
class Program
{
static void Main(string[] args)
{
var result = 1;
Console.WriteLine(result);
Console.ReadLine();
}
}
Output
Dynamic Keyword
Let us understand the features of the dynamic keyword in C#:
- It was introduced in C#4.0
- This is dynamically typed.
- There is no need to initialize at the time of declaration.
- Errors are caught at runtime.
- There is no Intellisense support.
- dynamic allows the type of value to change after it is assigned to initially.
Dynamic in C# Example:
class Program
{
static void Main(string[] args)
{
dynamic result = 1;
result = "Hi";
Console.WriteLine(result);
Console.ReadLine();
}
}
Here we have declared the result variable as dynamic and set it to an integer value. In the second line of code, we have assigned a string to it. This is as per point no 6 in the preceding differences.
let us run the program and check the output.
So these are the basic differences between var and dynamic keywords in C#.
Further Reading
This was a quick introduction to var and dynamic keywords in C# along with the differences between them.
If you want to read more about these keywords, you may refer to Microsoft’s documentation.
⭐C# Mastery – Mosh Hamedani
One of the best courses to master your C# skills right from level zero. This series is divided into 4 sections:
- C# Basics
- C# Intermediate
- C# Advanced
- Unit Testing for C# Developers
Summary
Few takeaway points related to var and dynamic keywords in C#:
- var keyword was introduced in C#3.0 while dynamic keyword in C#4.0
- Using var keyword, errors are caught during compile-time whereas with dynamic it’s run-time
- Variable declared using var keyword needs to be initialized at the time of declaration which is not the case with dynamic keyword.
I hope this post helped you to understand the basic difference between var and dynamic in C#.
Please share it with your developer friends and colleagues.