Medium10 minType Systems
UpdatedAug 2, 2026
Edit

var vs dynamic

Question Variations

  • "What is the difference between `var` and `dynamic` in C#?"
  • "Is `var` dynamic? (Explain compile-time inference vs runtime binding)"
  • "When would you use `dynamic` over `object` or `var`?"
  • "What are the performance implications of using `dynamic`?"

Why This Is Asked

This tests understanding of static vs dynamic typing within a statically-typed language. It’s important to know when to use type inference (var) and when to opt into late-binding (dynamic), especially for Interop or JSON scenarios.

Key Concepts

  • var is statically typed; the type is determined by the compiler at compile-time.
  • dynamic is dynamically typed; the type is resolved at runtime.
  • var has full IntelliSense support; dynamic does not.
  • dynamic bypasses compile-time type checking, which can lead to runtime exceptions if members don’t exist.

Question Variations

  • “What is the difference between var and dynamic in C#?”
  • “Is var dynamic? (Explain compile-time inference vs runtime binding)”
  • “When would you use dynamic over object or var?”
  • “What are the performance implications of using dynamic?”

Answers by Technology

+ Add Variant

Expected Answer (.NET 10 / C# 14)

Both var and dynamic allow for flexible variable declaration, but they behave differently:

  1. var (Type Inference):
    • The type is determined by the compiler at compile-time based on the initialization.
    • Once assigned, the type is fixed and cannot change.
    • It is just syntactic sugar; the resulting IL code is identical to using the explicit type.
  2. dynamic (Late Binding):
    • The type is resolved at runtime.
    • You can assign any value to it, and change it later.
    • The compiler skips type checking; if you call a method that doesn’t exist, it throws a RuntimeBinderException.

Why It Matters

Use var whenever the type is obvious from the right-hand side of the assignment (e.g., var list = new List<string>()) to keep code clean. Use dynamic sparingly, typically for COM Interop, Reflection, or when handling dynamic JSON objects without a fixed schema.

Code Example

// var: Static typing
var name = "John"; 
// name = 123; // Compile Error!

// dynamic: Dynamic typing
dynamic anything = "Hello";
anything = 123; // Works!
anything.NonExistentMethod(); // Compiles, but crashes at RUNTIME

Common Mistakes

  • Using dynamic for performance: dynamic is slower because it involves runtime overhead (DLR - Dynamic Language Runtime).
  • Using var when type isn’t clear: var x = GetResult(); can be hard to read if GetResult() isn’t clearly named.

Follow-up Questions

  • Does var affect performance? (Answer: No, it is resolved at compile-time).
  • Is object the same as dynamic? (Answer: No. object requires casting to access members; dynamic does not, as it assumes the members will be there at runtime).

Expected Answer (Java 26)

Java is a statically typed language and does not have a dynamic keyword like C#. However, it has var for type inference.

  1. var (Local Variable Type Inference):
    • Introduced in Java 10.
    • The compiler infers the type at compile-time based on the initializer.
    • The type is fixed and cannot change.
    • Only allowed for local variables with initializers.
  2. Dynamic Behavior (Java equivalents):
    • Java uses Reflection or MethodHandles for late-binding.
    • Frameworks like Spring use CGLIB or Dynamic Proxies to handle dynamic behavior at runtime.
    • You can use Object, but it requires explicit casting or instanceof checks.

Why It Matters

Use var to reduce boilerplate code, especially with complex generic types (e.g., Map<String, List<User>>). Java’s lack of a dynamic keyword is a design choice to maintain strict type safety and performance, forcing developers to use structured patterns like Reflection only when absolutely necessary.

Code Example

// var: Static typing (Type is inferred as String)
var name = "Alice";
// name = 123; // Compile Error!

// Java "Dynamic" style (using Object and Type Checking)
Object mystery = "Hello";
if (mystery instanceof String s) { // Java 17 Pattern Matching
    System.out.println(s.toUpperCase());
}

Common Mistakes

  • Using var for readability: var result = service.process(); can be confusing if the return type isn’t obvious.
  • Using var without initializer: var x; will not compile because there’s nothing to infer the type from.

Follow-up Questions

  • Does var affect runtime performance? (Answer: No, it is purely a compile-time feature).
  • Can var be used for class fields? (Answer: No, only for local variables inside methods).

Expected Answer (PHP 8.5)

PHP is a dynamically typed language, meaning variables don’t have a fixed type. However, it has moved toward “Gradual Typing.”

  1. Dynamic Typing: Variables can change types at any time. $x = "hello"; $x = 123;.
  2. Type Hinting: You can (and should) enforce types for function parameters, return values, and class properties.
  3. mixed type: Introduced in PHP 8.0, it represents “any type,” similar to dynamic in C#, but it’s a hint rather than a runtime behavior change.

Why It Matters

Modern PHP (8.x) is much stricter than older versions. While variables are still dynamic, properties and method signatures are usually strictly typed. This gives you the flexibility of a dynamic language with the safety of a static one.

Code Example

// Dynamic behavior
$val = "Start";
$val = ["Now I am an array"];

// Strict typing (Modern PHP)
class User {
    public function __construct(
        public string $name, // Type Hinting
        public int|float $score // Union Types (PHP 8.0)
    ) {}
}

Common Mistakes

  • Not using declare(strict_types=1);: Without this, PHP will still try to coerce types (e.g., passing "5" to an int parameter).
  • Over-using mixed: It’s a “get out of jail free” card that should be used sparingly when you truly don’t know the type.

Follow-up Questions

  • What are Union Types? (Answer: Allowing a variable to be one of several types, e.g., string|int).
  • What is Type Coercion? (Answer: PHP’s automatic conversion between types, like treating a non-empty string as true in an if statement).