Var vs Dynamic in C#

Var vs Dynamic in C# with Examples

In this article, I am going to discuss Var vs Dynamic in C# with Examples. Before proceeding with this article, I strongly recommended you read our Dynamic Type in C# and VAR Keyword in C# articles. At the end of this article, you will understand the differences between VAR and Dynamic and when to use VAR, and when to use Dynamic in C# with Examples.

Var vs Dynamic in C#

In simple words, we can say that var is early bounded (in other words it is statically checked) whereas Dynamic is late bounded (in other words it is checked on runtime) or you can say it is dynamically evaluated.

Let us understand the differences between the Var vs Dynamic Keywords in C# with an example. Please have a look at the below example. Here, I have declared one variable called x using the var keyword and assigned the value string1. Then I declared one integer variable Len to hold the length of the x variable. Here, I am calling the Length function on the x object.

namespace VarVSDynamicDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var x = "String1"; //Early Bounded
            int Len = x.Length;
        }
    }
}

The first thing that you need to notice here is, that when we type x and dot (.), you will notice that intelligence is coming and you can see the Length function as shown in the below image.

Var vs Dynamic in C#

And if you move the mouse pointer over the x variable, you will see that it is saying that x is a local variable whose data type is a string as shown in the below image.

Var vs Dynamic in C#

So, in other words, the compiler figures out the x data type is a string. The compiler looks at the right-hand side data (i.e. string1) and figures out the x data type as a string. For a better understanding, please have a look at the below image.

Var vs Dynamic in C# with Examples

The Var keyword is early bounded or statically checking. It means at the time we write the code using the var keyword and compile it, the compiler knows what the data type is.

Now, let us do the same thing using dynamic type. This is the same example as the previous one, except here we use the dynamic keyword instead of the var keyword. So, here, I have declared one variable called x using the dynamic keyword and assigned the value string1. Then I declared one integer variable Len to hold the length of the x variable. Here, I am calling the Length function on the x.

namespace VarVSDynamicDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic x = "String1"; //Late Bounded
            int Len = x.Length;
        }
    }
}

The first thing that you need to notice here is that when we type x and dot (.), you will not get any intelligence and you cannot see the Length function as shown in the below image.

Var vs Dynamic in C# with Examples

And if you move the mouse pointer over the x variable, you will see that it is saying that x is a local variable whose data type is dynamic as shown in the below image. That means it is still not figuring out what is the data type of x.

Var vs Dynamic in C# with Examples

Example to understand VAR and Dynamic in C#:

Now, let us execute the following code in debug mode.

using System;
namespace VarVSDynamicDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var v = "String1"; //Late Bounded
            int Len1 = v.Length;
            Console.WriteLine($"Using Var, Value={v} and Length={Len1}");

            dynamic d = "String1"; //Late Bounded
            int Len2 = d.Length;
            Console.WriteLine($"Using Dynamic, Value={d} and Length={Len2}");

            Console.ReadKey();
        }
    }
}

Executing the statements using the var keyword is straightforward. This is because property binding i.e. invoking the Length property on v object is bounded at the compilation time. This is because the compiler knows there is a property called Length available in the string class. But this is not the case with dynamic type. So, what happens with dynamic type is, at runtime, y variable dynamically goes and uses reflection internally and tries to invoke the property dynamically. If the property exists, it will execute and if it does not exist then it will throw a runtime exception. In our example, the Length property exists in the string class and hence it will execute that property.

Example to understand VAR and Dynamic in C#

So, when you execute the above code, you will get the following output as expected.

Example to understand VAR and Dynamic in C#

Now, let us do a small mistake, instead of Length (capital L), let us use length (small l) and see what happens. See, with var, we are getting compile time error immediately. But, with dynamic, we are not getting any compile time error. This is because the binding has not happened at the compile time.

Example to understand VAR and Dynamic in C#

Let us try to use capital L with the var keyword and small l with the dynamic keyword as shown in the below code and try to run the application.

namespace VarVSDynamicDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var v = "String1"; //Late Bounded
            int Len1 = v.Length;
            
            dynamic d = "String1"; //Late Bounded
            int Len2 = d.length;
        }
    }
}

You can observe that we are not getting any compilation errors. But when we run the code, we will get the following Runtime Exception. This is because, at runtime, d internally uses the reflection mechanism to invoke the length property of the string class. But in string class, there is no property length (with small l) and hence it will throw a runtime error.

difference between var and dynamic in C#

So, the difference between var and dynamic is that var is early bounded (it is statically checked or you can say it is checked at compilation time) whereas dynamic is late bounded (the methods, the properties, the type, everything will be checked at runtime).

Note: The most important point that you need to remember is dynamic keyword uses Reflection.

Can we use var and dynamic as a return type or parameter of a function in C#?

We can not use the var keyword either as a return type of a function or a parameter of a function in C#. The var keyword can only be used as a local variable inside a function. If we try to use the var keyword either as a method parameter or method return type, we will get a compiler time error.

For a better understanding, please have a look at the below example. Here, we are trying to use var as the return type of the SomeMethod as well as using var as the parameters of the SomeMethod.

using System;
namespace VarVSDynamicDemo
{
    class Program
    {
        static void Main(string[] args)
        {
        }

        static var SomeMethod(var x, var y)
        {
            return x + y;
        }
    }
}

When you compile the above code, you will get the following compilation error.

Can we use var and dynamic as a return type or parameter of a function in C#?

As you can see, it is clearly saying that you can only var as a local variable declaration. That means you cannot use var either method return type of method parameter. Now, let us rewrite the same example using the dynamic keyword as follows.

using System;
namespace VarVSDynamicDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(SomeMethod(10, 20));
            Console.ReadKey();
        }

        static dynamic SomeMethod(dynamic x, dynamic y)
        {
            return x + y;
        }
    }
}

Output: 30

Now, with dynamic, we are not getting any compilation error or runtime error. That means we can use dynamic as a local variable, as the method return type as well as the method parameter. This is one of the biggest differences between var and dynamic in C#.

Differences Between Var and Dynamic in C#:

Now, let us summarizes the differences between var and dynamic in C#. The differences are as follows:

Var in C#
  1. var is known as a statically typed variable which means that the data type of these variables is identified at compile time which is done based on the type of value that these variables are initialized with.
  2. var in C# was introduced as part of C#3.0.
  3. In the case of var, the data type of the variable is identified by the compiler at the compilation time only.
  4. In the case of var, it is mandatory to initialize the variable at the time of its declaration, so that the compiler comes to know the data type of the variable according to the right-hand side value assigned to it.
  5. It will throw an error if the variable does not initialize at the time of its declaration.
  6. We will get intelligence support in the visual studio.
  7. Var cannot be used for properties or returning values from the function in C#. It can only use as a local variable inside a function.
  8. Var is early bounded. This means the type of variable declared is decided by the compiler at compile time.
Dynamic in C#
  1. Dynamic is the dynamically typed variables which clearly implies that their type is inferred at run-time and not the compile time.
  2. Dynamic in C# was introduced in C#4.0.
  3. In the case of dynamic, the data type of variable is identified by the compiler at run time.
  4. In the case of dynamic, it is not mandatory to initialize the variable at the time of its declaration.
  5. It will not throw an error if the variable does not initialize at the time of its declaration.
  6. We will not get any intelligence support in the visual studio.
  7. Dynamic can be used for properties or returning values from the function in C#.
  8. Dynamic is Late Bounded. This means the type of variable declared is decided by the compiler at runtime time.

In the next article, I am going to discuss Reflection vs Dynamic in C# with Examples. Here, in this article, I try to explain Var vs Dynamic in C# with Examples. I hope you enjoy this Var vs Dynamic in C# with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

1 thought on “Var vs Dynamic in C#”

  1. blank

    Guys,
    Please give your valuable feedback. And also, give your suggestions about this Var vs Dynamic in C# concept. If you have any better examples, you can also put them in the comment section. If you have any key points related to Var vs Dynamic in C#, you can also share the same.

Leave a Reply

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