Difference Between Var And Dynamic In C#

In this tutorial, we will explore the var and dynamic keywords in C# and delve into their distinctions. To comprehend these disparities effectively, it is crucial to grasp the concepts of var and dynamic in C#. At the onset of programming in any language, a pivotal step is the declaration of variables, their conceptual understanding, and subsequent utilization. Hence, understanding variable declaration in the programming language is a fundamental aspect before commencing with code composition.

In earlier iterations of C#, all written code undergoes self-validation during compilation. C# remains a statically typed language, requiring the use of the var keyword for variable declaration. Starting from C# 4.0 and beyond, the concept of "dynamic" was introduced, allowing for syntax validation and error detection to take place solely at runtime. This change also brought about the introduction of the "Dynamic" keyword for declaring variables.

What is the Var Keyword?

An automatically inferred local variable (var) is a variable declared without explicitly mentioning a specific .NET data type. With implicit typing, the variable's type is determined based on the assigned value during initialization at compile time. The concept of implicitly typed variables was introduced in C# 3.0. These variables are designed to cater to particular scenarios such as LINQ (Language Integrated Query) without aiming to substitute traditional variable declarations.

Syntax:

It has the following syntax:

Example

var x=1// int type
var str="String". //string type
var d=10.9 // Double

Example:

Let's consider a scenario to demonstrate the use of the Var keyword in C#.

Example

using System; 
class VarKeyword
{ 
    // Main method 
    static public void Main()
    { 

    // the variables 
    //declaration using var keyword 
    var a1 = 'v'; 
    var a2 = "VarKeyword"; 
    var a3 = 34.69d;
    var a4= false; 
    var a5 = 54594; 
    //The console statement to display the output and its type
    Console.WriteLine("The type of 'a1' is  {0} ", a1.GetType());
    
    Console.WriteLine("The type of 'a2' is {0} ", a2.GetType()); 
    
    Console.WriteLine("The type of 'a3' is {0} ", a3.GetType()); 
    
    Console.WriteLine("The type of 'a4' is {0} ", a4.GetType());
    
    Console.WriteLine("The type of 'a5' is {0} ", a5.GetType()); 
    }
}

Output:

Output

The type of 'a1' is System.Char 
The type of 'a2' is System.String 
The type of 'a3' is System.Double 
The type of 'a4' is System.Boolean 
The type of 'a5' is System.Int32

Explanation:

In this instance, the code demonstrates the utilization of the Var keyword. This keyword enables users to declare variables without explicitly specifying the data type, as the compiler can infer it automatically. The variables are defined, and the script employs the console statement to showcase the datatype associated with the var keyword.

What is the Dynamic Keyword?

A fresh dynamic keyword was added in C# 4.0 to allow for dynamic typing. Variables declared as dynamic have their types determined dynamically during program execution. Initialization of dynamic variables is not mandatory upon declaration. Since the compiler is unaware of the variable types during compile time, any errors related to it cannot be detected until runtime. The lack of IntelliSense support is a consequence of the dynamic type being established only at runtime.

Just like the var keyword in C#, the dynamic keyword serves the purpose of declaring variables without explicitly mentioning a data type. While the Var variable gets assigned a type during compilation, it transforms into a Dynamic Variable during runtime.

Example 1:

Example

dynamic l = 1090; // int data type 
dynamic m = "Dynamic";// string type 
dynamic n = 18.90; // double data type

Example 2:

Example

dynamic ob= "dynamic keyword"; 
obj = 20;

When an integer is assigned to ```

var x=1// int type

var str="String". //string type

var d=10.9 // Double

Example

var x=1// int type
var str="String". //string type
var d=10.9 // Double

var x=1// int type

var str="String". //string type

var d=10.9 // Double

Example


### Example:

Let's consider a scenario to demonstrate the Dynamic Keyword in C#.

using System;

class Dynamic

{

// Main Method

static public void Main

{

// the variable declaration

dynamic v1 = "DynamicKeyword";

dynamic v2 = 32674;

dynamic v3 = 62.45;

dynamic v4 = true;

// by using the val.GetType method

//to obtain the exact datatype

Console.WriteLine("The actual datatype of v1: {0}",v1.GetType.ToString);

Console.WriteLine("The actual datatype of v2: {0}",v2.GetType.ToString);

Console.WriteLine("The actual datatype of v3: {0}", v3.GetType.ToString);

Console.WriteLine("The actual datatype of v4: {0}", v4.GetType.ToString);

}

}

Example


Output:

The actual datatype of v1: System.String

The actual datatype of v2: System.Int32

The actual datatype of v3: System.Double

The actual datatype of v4: System.Boolean

Example


Explanation:

In this instance, the dynamic keyword is employed to declare variables where their data types are determined during runtime rather than at compile time. Within the provided code snippet, v1, v2, v3, and v4 are explicitly declared with the dynamic keyword and their types are determined using the GetType() method. The outcome is then transformed into a string by invoking the ToString() method.

## Main Differences between Var and Dynamic in C#

The diagram below illustrates the styling for a placeholder element:

.placeholder-diagram { background: linear-gradient(135deg, #374151 0%, #1f2937 100%); border-radius: 12px; padding: 40px; margin: 20px 0; text-align: center; }

.placeholder-diagram .placeholder-icon { font-size: 3rem; margin-bottom: 10px; }

.placeholder-diagram .placeholder-text { color: #9ca3af; font-size: 1rem; }

Example


There are multiple variances between var and dynamic in C#. Some key distinctions include:

| Var | Dynamic |
| --- | --- |
| Var in the C# language was introduced in C#3.0 | Dynamics was introduced later in C#4.0 |
| Variables are declared using the statically typedvar keyword. | Variables are declared using the dynamic keyword, which is dynamically typed. |
| Variables are assigned to the compiler for interpretation at compilation. | The compiler decides the type of variables during runtime. |
| This variable type must be initialized at declaration time. The variable is assigned a type by the compiler, which takes into use and its initialization. | This variable type does not need to be initialized at declaration time. During compilation, the variable's type is unknown to the compiler. |
| If the variable is not initialized, an error is thrown. | If the variable is not initialized, no error occurs. |
| IntelliSenseis supported in Visual Studio. | Visual Studio doesn't support IntelliSense. |
| variable temp = 100;temp = "Program";The compiler returns an error because the type of the temporary variable was already determined by statement 1, and it is of type integer. The compiler displays a warning when you assign a string to a 'temporary variable', which implies that security measures cannot be violated. | dynamic temp = 100;temp = "Programming";The compiler does not return an error even if temp is of type integer.Assigning a string to "temp" recreates the type "temp" and accepts the string successfully. |

## Conclusion:

In this guide, we have explored the Var and Dynamic keywords in C#. Each serves a distinct role in declaring variables, offering flexibility based on the specific needs of the program.

Input Required

This code uses input(). Please provide values below: