Language: EN

csharp-dynamics

Dynamics in C#

The dynamic type is a feature introduced in C# 4.0 that allows for dynamic programming. It enables us to resolve types and members at runtime instead of at compile time.

The dynamic type is a data type that 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, allowing for greater flexibility in certain programming scenarios.

Using dynamic provides flexibility to work with types that may not be known until the program is executed.

Basic Syntax

The dynamic type is declared similarly to other types in C#, using the dynamic keyword.

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 value = 10;
Console.WriteLine(value + 5); // Valid operation, output: 15

value = "Hello";
Console.WriteLine(value + " World!"); // Valid operation, output: Hello World!

In the first case, value 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 may occur due to type errors.

try
{
    dynamic value = "text";
    int number = value; // 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 coming 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: Using dynamic skips type checks at compile time, which can lead to runtime errors that would be avoidable with statically defined types.
  • Less 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 value = "123";
int number = int.Parse(value); // Explicit conversion

value = 456;
int anotherNumber = value; // Implicit conversion

Practical Example: JSON Data Processing

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 needing to define a data class beforehand.