What is dynamic in C#: Explanation and Examples
dynamic in C# is a type that bypasses compile-time type checking, allowing operations to be resolved at runtime. It lets you write flexible code that can work with objects whose types are not known until the program runs.How It Works
Imagine you have a toolbox but you don’t know exactly what tools you will need until you start fixing something. dynamic in C# works like that toolbox. Instead of telling the computer exactly what type of object you are using when you write the code, you tell it to wait and figure it out when the program runs.
This means the computer skips checking if the methods or properties you use exist on the object during compilation. Instead, it looks for them when the program is running. This can be helpful when working with data from outside sources or when you want to write very flexible code.
Example
This example shows how dynamic lets you call methods or access properties without the compiler checking types first.
using System; class Program { static void Main() { dynamic obj = "Hello, world!"; Console.WriteLine(obj.Length); // Works because string has Length obj = 12345; // Console.WriteLine(obj.Length); // This would cause a runtime error because int has no Length obj = new { Name = "Alice", Age = 30 }; Console.WriteLine(obj.Name); // Access anonymous type property } }
When to Use
Use dynamic when you need flexibility and cannot know the exact types at compile time. 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, be careful because errors related to missing methods or properties will only show up when the program runs, not when you write the code.
Key Points
- Dynamic typing: Type checks happen at runtime, not compile time.
- Flexibility: Allows working with objects of unknown types.
- Risk: Runtime errors if members don’t exist.
- Use cases: Interoperability, dynamic data, simplifying reflection.
Key Takeaways
dynamic defers type checking to runtime, enabling flexible code.dynamic can cause runtime errors if members are missing or mistyped.dynamic for interoperability and simplifying complex type handling.dynamic to keep code safe and maintainable.