What if we are not sure of the type of value that we want to store in a variable. How to handle this in C#?

As C# is a strongly-typed language, every variable and constant has a pre-defined type. Before using any variable, we must tell the compiler what type of value a variable will store.

If we are not sure about the type, then it is handled using dynamic programming. Dynamic programming is supported by the dynamic keyword, which allows variables to bypass compile-time type checking and have their types resolved at runtime.

Syntax

Following is the syntax for declaring a dynamic variable −

dynamic variableName = value;

The type of the variable is determined at runtime based on the assigned value −

dynamic myVar = 100;        // Runtime type: int
dynamic myVar = "Hello";    // Runtime type: string
dynamic myVar = true;       // Runtime type: bool

How It Works

The dynamic keyword tells the compiler to skip type-checking at compile time and defer type-checking until runtime. All syntax validation occurs at runtime, which means errors related to type mismatches or invalid operations will be thrown during program execution rather than compilation.

Static vs Dynamic Type Checking Static Typing int x = 10; Type checked at compile time Errors caught early Dynamic Typing dynamic x = 10; Type resolved at runtime Flexible but riskier Both approaches have their use cases in C# development

Using Dynamic Variables

Example

using System;

namespace DemoDynamicKeyword {
    class Program {
        static void Main(string[] args) {
            dynamic MyDynamicVar = 100;
            Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar, MyDynamicVar.GetType());
            
            MyDynamicVar = "Hello World!!";
            Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar, MyDynamicVar.GetType());
            
            MyDynamicVar = true;
            Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar, MyDynamicVar.GetType());
            
            MyDynamicVar = DateTime.Now;
            Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar, MyDynamicVar.GetType());
        }
    }
}

The output of the above code is −

Value: 100, Type: System.Int32
Value: Hello World!!, Type: System.String
Value: True, Type: System.Boolean
Value: 1/1/2024 12:00:00 AM, Type: System.DateTime

Dynamic vs Object vs Var

Keyword Type Resolution Performance IntelliSense Support
dynamic Runtime Slower (runtime overhead) No
object Compile-time (base type) Requires boxing/unboxing Limited
var Compile-time (inferred) Fast (strongly typed) Yes

Example

using System;

class Program {
    static void Main() {
        // var - type inferred at compile time
        var varExample = 42;
        // varExample = "string"; // Compile error!
        
        // object - stores any type but requires casting
        object objExample = 42;
        int objValue = (int)objExample; // Casting required
        
        // dynamic - type resolved at runtime
        dynamic dynExample = 42;
        dynExample = "Now I'm a string!"; // No compile error
        
        Console.WriteLine("var: {0}", varExample);
        Console.WriteLine("object: {0}", objValue);
        Console.WriteLine("dynamic: {0}", dynExample);
    }
}

The output of the above code is −

var: 42
object: 42
dynamic: Now I'm a string!

Common Use Cases

  • COM Interop: Working with Microsoft Office applications or other COM objects.

  • JSON/XML Processing: Handling dynamic data structures from web APIs.

  • Reflection-heavy scenarios: When working extensively with types unknown at compile time.

  • Third-party libraries: Integrating with libraries that expose dynamic APIs.

Conclusion

The dynamic keyword in C# provides flexibility when the type of a variable is unknown at compile time. While it offers runtime type resolution and eliminates casting, it comes with performance overhead and reduced compile-time safety, so it should be used judiciously in appropriate scenarios.

Updated on: 2026-03-17T07:04:36+05:30

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements