The dynamic
type is a feature introduced in C# 4.0 that enables dynamic programming. It allows us to resolve types and members at runtime instead of at compile time.
That is, the dynamic
type skips static type checking at compile time and delegates the resolution of types and members to runtime.
This means that operations on dynamic
type variables are not validated until the program is running. This allows for great flexibility in certain programming scenarios.
However, it also has many detractors. It means skipping some of the strong typing guidelines, which many developers dislike (in fact, it wasn’t particularly successful and is somewhat out of use)
Basic Syntax
The dynamic
type is declared similarly to other types in C#, using the dynamic
keyword as the type.
dynamic variable = 10;
variable = "Hello, World!";
variable = new List<int> { 1, 2, 3 };
In this example, variable
can hold different types of values, and the actual type of the variable is resolved at runtime.
Operations with dynamic
When performing operations with a dynamic
type variable, the compiler does not perform any type checking. Instead, operations are resolved at runtime.
dynamic valor = 10;
Console.WriteLine(valor + 5); // Valid operation, output: 15
valor = "Hello";
Console.WriteLine(valor + " World!"); // Valid operation, output: Hello World!
In the first case, valor
is treated as an integer, while in the second case, it is treated as a string.
Exception Handling
Since dynamic
operations are resolved at runtime, it is especially important to be aware of exceptions that can occur due to type errors.
try
{
dynamic valor = "texto";
int numero = valor; // Will cause a runtime exception
}
catch (RuntimeBinderException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Advantages and Disadvantages of Using dynamic
Advantages
Flexibility: Allows working with data types that are not known at compile time, which is useful when interacting with COM libraries, reflection libraries, dynamic APIs, or data from external sources like JSON or XML.
Code Simplification: Avoids the need for explicit conversions and casting, making it easier to write code that interacts uniformly with different data types.
Disadvantages
- Performance:
dynamic
operations can be slower due to the need to resolve types at runtime. - Loss of Type Safety: The use of
dynamic
skips type checks at compile time, which can lead to runtime errors that would be avoidable with statically defined types. - Reduced Clarity: Code with
dynamic
can be harder to understand and maintain due to the lack of type information at compile time.
Practical Examples
Interaction with COM Types
Using dynamic
is especially useful when working with COM libraries where types are not known at compile time:
dynamic excel = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
excel.Visible = true;
excel.Workbooks.Add();
excel.Cells[1, 1].Value = "Hello World";
Implicit and Explicit Conversion
dynamic
variables can be converted implicitly or explicitly to other types:
dynamic valor = "123";
int numero = int.Parse(valor); // Explicit conversion
valor = 456;
int otroNumero = valor; // Implicit conversion
Processing JSON Data
A common practical case for dynamic
is processing JSON data:
using System;
using System.Dynamic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
class Program
{
static async Task Main(string[] args)
{
string url = "https://api.example.com/data";
using HttpClient client = new HttpClient();
string jsonData = await client.GetStringAsync(url);
dynamic data = JsonConvert.DeserializeObject<ExpandoObject>(jsonData);
Console.WriteLine(data.Name);
Console.WriteLine(data.Age);
}
}
In this example, dynamic
is used to deserialize JSON data into a dynamic object, allowing direct access to properties without the need to define a data class beforehand.