C# Dynamic Type: Var vs dynamic keywords in C#

The dynamic keyword is used to define dynamic types. Dynamic type is used to avoid compile-time type checking. The compiler does not type-check dynamic type variables at compile time, instead, the compiler check the type at the run time. If the syntax of the statement is invalid, an error will be thrown at runtime.

Dynamic types are similar to object types, despite the fact that type checking for object type variables occurs at compile time rather than at runtime for dynamic type variables.

csharp dynamic type
C# dynamic type

Why should we use the dynamic type in C#?

Dynamic type provides advantages, such as the ability to store data of any type and the flexibility to change the type at runtime. it has drawbacks as well, such as the lack of IntelliSense makes working with dynamic objects difficult when writing code.
The following situations are better suited for using dynamic type in c#.

  • Dynamic types can be used to interact with other dynamic languages.
  • The Dynamic Language Runtime (DLR) provides the infrastructure that supports the dynamic type in C#, It Simplifies responses from API calls when you don’t know the type of object you expect in response.
  • It can be used to create DLLs or libraries that can be shared and used between different programming languages.
  • The reflection code can be replaced and simplified by using dynamic.

Example 1:

Dynamic types variables change their types based on the value provided at runtime. The following example demonstrates how a dynamic variable’s type will change depending on its value.

using System;
namespace CSharp_Dynamic_Keyword_Example
{
    class Program
    {
      
        static void Main(string[] args)
        {
            // Declare Dynamic Type and assign integer value.
            dynamic dynamicVariable = 100;

            Console.WriteLine($"Value: {dynamicVariable} , Type { dynamicVariable.GetType()}");

            // Now change the value from integer to string.
                    dynamicVariable = "Hello";
            Console.WriteLine($"Value: {dynamicVariable} , Type {dynamicVariable.GetType()}");

            Console.ReadLine();
        // Output:
        // Value: 100 , Type System.Int32
        // Value: Hello , Type System.String
            
        }
    }
}

Example 2:

To allow a method to accept any parameters at runtime, you can pass a dynamic parameter type to the method. As shown in the example below.

using System;
namespace CSharp_Dynamic_type_Example
{
    class Program
    {
        // Method contains dynamic parameters
        public static void AddValues(dynamic value1, dynamic value2)
        {
            Console.WriteLine(value1 + value2);
        }

        static void Main(string[] args)
        {
            // Calling AddValues method

            AddValues("Hello ", "Shekh");
            AddValues("Numbers", 123);
            AddValues(10, 30);

            Console.ReadLine();

            // Output:
            // Hello Shekh
            // Numbers123
            // 40

        }
    }
}

Differences between var and dynamic in C#

The following are some differences between the var and dynamic keywords in C#:

Sr.No.Var keywordDynamic keyword
1.Var keyword was introduced with C# 3.0 release.The dynamic type was introduced with C# 4.0 release.
2.Var is type-safe, meaning the compiler has access to all information about the stored value, ensuring that there won’t be any problems during run-time.It is not type-safe, meaning that the compiler does not know the type of the variable at the time of compilation.
3.Variables of the type var must be initialized at the time of declaration or else they will cause a compilation time error.Dynamic type variables do not need to be initialized when they are declared.
4.The type of a value cannot be changed once it has been assigned to a var variable.On the other hand, a dynamic variable allows the type of value to change after it has been assigned.
5.The var type of variables can use IntelliSense since the compiler already has all the information necessary to support it.While Dynamic type variables do not have access to Intellisense since the type of the variable is not known until run time.
6.Var variable can only be used as a local variable inside a method. It cannot be used for properties or returning values from the method.You can use dynamic variables to create properties and return values ​​from functions.
Var Vs Dynamic Keywords In C#

FAQ

Q: What is a C# dynamic type?

The dynamic type was introduced with the release of C# 4.0 to bypass the type checking during compilation time. The compiler does not check the type of the dynamic type variable at compile time, Instead, the type is resolved during the run time.

Q: Is it advisable to use dynamic type in C#?

The dynamic type is useful when interacting with COM or dynamically typed languages such as Python, Ruby, and JavaScript. A dynamic variable can store any type, and based on the value that has been assigned, the type can change at runtime.

Q: Is C# statically typed or dynamically typed language?

C# is primarily a statically typed language because the compiler determines the types of every expression. It is a type-safe language because it restricts the values of one static type from being stored in variables of an incompatible type.

Q: How can we get the actual type of a dynamic variable?

The GetType() method can be used to get the actual type of the dynamic variable.

References: MSDN-Using type dynamic

I hope you enjoyed reading this article “C# Dynamic Type“. If you think it’s interesting, please share it with others. If you have any further information to provide about the topics covered here, please leave a comment.

Articles to Check Out:

Shekh Ali
4 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments