Language: EN

csharp-dynamics

Dynamics in C#

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

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