0
0
CsharpConceptBeginner · 3 min read

What is dynamic keyword in C#: Explanation and Examples

The dynamic keyword in C# allows variables to bypass compile-time type checking, deferring type resolution to runtime. This means you can write flexible code that works with objects whose types are not known until the program runs.
⚙️

How It Works

Imagine you have a box, but you don't know what's inside until you open it. The dynamic keyword in C# works like that box. Normally, C# checks the type of every variable before running the program to catch mistakes early. But with dynamic, the program waits until it is running to figure out what type the variable really is.

This means you can call methods or access properties on a dynamic variable without the compiler checking if those methods or properties exist. If they don't exist at runtime, the program will throw an error then. This gives you more flexibility but also more responsibility to avoid mistakes.

💻

Example

This example shows how a dynamic variable can hold different types and call methods without compile-time checks.

csharp
using System;

class Program
{
    static void Main()
    {
        dynamic value = "Hello";
        Console.WriteLine(value.Length); // Works: string has Length

        value = 123;
        Console.WriteLine(value + 10); // Works: int supports +

        value = new { Name = "Alice" };
        Console.WriteLine(value.Name); // Works: anonymous type has Name

        // Uncommenting the next line will cause runtime error if property doesn't exist
        // Console.WriteLine(value.Age);
    }
}
Output
5 133 Alice
🎯

When to Use

Use dynamic when you need flexibility to work with objects whose types are not known until runtime. For example, when working with JSON data, COM objects, or dynamic languages like Python through interop.

It is also useful when you want to simplify code that would otherwise require many casts or reflection calls. However, avoid dynamic if you want the compiler to catch type errors early or if performance is critical, because runtime checks add overhead.

Key Points

  • Dynamic disables compile-time type checking.
  • Type is resolved at runtime.
  • Allows flexible code with unknown types.
  • Runtime errors occur if members don't exist.
  • Use carefully to avoid bugs and performance hits.

Key Takeaways

The dynamic keyword defers type checking to runtime, allowing flexible code.
Use dynamic when working with unknown or changing types like JSON or COM objects.
Dynamic variables can call any method or property, but errors appear only at runtime.
Avoid dynamic if you want early error detection or better performance.
Dynamic simplifies code but requires careful use to prevent runtime bugs.