Var vs Dynamic in C#

Introduction to Var and Dynamic

In C#, both **var** and **dynamic** provide flexibility in variable declarations. However, they function differently in terms of **type resolution and type safety**.

  • var: The compiler determines the type **at compile-time**, enforcing type safety.
  • dynamic: The type is **resolved at runtime**, allowing for greater flexibility but reducing type safety.

Understanding var in C#

The **var** keyword allows **implicit typing**, where the **compiler infers the variable's type** based on the assigned value. However, once inferred, **the type remains fixed**.

Example: Using var

var number = 100;   // Compiler infers 'int'
var name = "Alice";  // Compiler infers 'string'

Console.WriteLine(number.GetType());  // Output: System.Int32
Console.WriteLine(name.GetType());    // Output: System.String
        

The **compiler enforces type safety** at compile-time. Attempting to change the type **will cause a compile-time error**.

Understanding dynamic in C#

The **dynamic** keyword **defers type checking** to **runtime**, allowing the variable to **change types dynamically**.

Example: Using dynamic

dynamic value = 50;  // Initially an int
Console.WriteLine(value.GetType());  // Output: System.Int32

value = "Hello";  // Now a string
Console.WriteLine(value.GetType());  // Output: System.String
        

Unlike var, **dynamic variables can change types at runtime**, but this may lead to **runtime errors if used incorrectly**.

Key Differences Between var and dynamic

Although **var** and **dynamic** both simplify variable declarations, their **usage and behavior differ significantly**.

Feature var dynamic
Type Resolution Determined at **compile-time** Determined at **runtime**
Type Safety Enforced **at compile-time** (strongly typed) Not enforced (can cause **runtime errors**)
Performance Faster (**no overhead** for type checking at runtime) Slower (**extra overhead** for runtime type resolution)
Flexibility Limited (**fixed type after initialization**) Highly flexible (**type can change at runtime**)
Common Use Cases When **the type is known or easily inferred** When **working with unknown types** (e.g., JSON, COM objects, Reflection)

When to Use var vs dynamic

  • Use var: When the type is **known or easily inferred**, ensuring **type safety**.
  • Use dynamic: When working with **unknown types**, such as **JSON data, reflection, or COM objects**.
  • Avoid Overusing dynamic: Overuse can lead to **runtime errors** and **performance issues**.

Real-World Use Cases

1. Using dynamic with JSON Data

When deserializing JSON, **dynamic allows flexible data access** without predefined classes.

dynamic jsonData = Newtonsoft.Json.JsonConvert.DeserializeObject("{\"Name\": \"Alice\", \"Age\": 25}");
Console.WriteLine(jsonData.Name);  // Output: Alice
        

2. Using var with LINQ Queries

**var simplifies complex LINQ queries** by **removing long type declarations**.

var numbers = new List { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);

foreach (var num in evenNumbers)
{
    Console.WriteLine(num);  // Output: 2, 4
}