Understanding the Dynamic Type in C#: Examples and Usage Scenarios

Category > CSHARP || Published on : Tuesday, March 7, 2023 || Views: 129 || C# Dynamic type Late-binding COM objects JSON data Newtonsoft.Json


C# is a statically typed language, but the dynamic type provides a way to declare a variable whose type is determined at runtime. In this article, we'll explore the dynamic type in C#, its syntax, and some usage scenarios, such as working with COM objects and JSON data.

Dynamic Type in C#: Introduction and Examples

C# is a statically typed language, which means that the type of a variable must be declared at compile time. However, sometimes it can be useful to defer the type declaration until runtime, when the type of the value is known. This is where the dynamic type in C# comes into play.

What is Dynamic Type in C#?

The dynamic type in C# allows you to declare a variable whose type is determined at runtime, instead of at compile time. The dynamic type is part of the .NET Framework 4.0 and later versions and is used to simplify programming scenarios that involve interoperability with dynamic languages, COM objects, and other scenarios where the type of an object is not known until runtime.

How to Declare Dynamic Type in C#?

To declare a dynamic variable, you use the dynamic keyword. Here's an example:

dynamic myVar = 1;
myVar = "Hello";
myVar = new MyClass();

In this example, the type of myVar is determined at runtime. The first assignment assigns an integer value to myVar, so its type is int. The second assignment assigns a string value to myVar, so its type changes to string. The third assignment assigns an instance of MyClass to myVar, so its type becomes MyClass.

Using Dynamic Type with COM Objects

One of the most common scenarios where the dynamic type is used is when working with COM objects. COM objects are objects that can be created and used by applications written in different languages, including C#. When working with COM objects, you typically need to use the late-binding technique, which involves calling methods and accessing properties of an object at runtime, based on the object's interface.

Here's an example:

dynamic excel = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
excel.Visible = true;
excel.Workbooks.Add();
excel.Cells[1, 1] = "Hello, World!";

In this example, we create an instance of Excel and set its Visible property to true. We then add a new workbook and write a value to cell A1.

Using Dynamic Type with JSON Data

Another scenario where the dynamic type is useful is when working with JSON data. JSON is a lightweight data interchange format that is widely used for data exchange between web applications and services. JSON data is typically represented as a dynamic object, which can be deserialized from a JSON string.

Here's an example:

dynamic json = JsonConvert.DeserializeObject(@"{
    'firstName': 'John',
    'lastName': 'Doe',
    'age': 25,
    'address': {
        'street': 'Main St',
        'city': 'New York',
        'state': 'NY'
    }
}");

string firstName = json.firstName;
string lastName = json.lastName;
int age = json.age;
string street = json.address.street;
string city = json.address.city;
string state = json.address.state;

In this example, we deserialize a JSON string into a dynamic object using the JsonConvert class from the Newtonsoft.Json package. We then access the properties of the dynamic object using dot notation.

Conclusion

The dynamic type in C# provides a flexible and powerful way to work with dynamic objects and data, such as COM objects and JSON data. By allowing you to defer type declaration until runtime, the dynamic type simplifies programming scenarios that involve interoperability with dynamic languages and other scenarios where the type of an object is not known until runtime.