What is the usage of dynamic in C#?
In C#, the dynamic keyword is used to represent a dynamic type. Variables declared using the dynamic keyword can be bound to any type of object at runtime, and can access any members of that object without the need for compile-time type checking.
Variables of type dynamic do not undergo type checking at compile time, but are resolved at runtime. This makes it easier to write flexible code that can handle objects of different types.
Dynamic type variables can be used in the following scenarios:
- Interacting with dynamic languages: When interacting with dynamic languages like Python, you can use the dynamic type to handle the returned objects, allowing you to call their members in C# code.
- Handling Reflection: The dynamic type can be used to simplify reflection operations. By using dynamic types, you can call an object’s members at runtime without the need for reflection APIs.
- Working with COM objects: The dynamic type can be used to interact with COM objects. COM objects use dynamic dispatch, allowing the use of the dynamic type to call the members of COM objects.
Here is an example of the dynamic type:
dynamic obj = "Hello World";
Console.WriteLine(obj); // 输出:Hello World
obj = 10;
Console.WriteLine(obj + 5); // 输出:15
obj = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine(obj.Count); // 输出:5
In the example above, the variable obj is declared as dynamic type, allowing it to be bound to different types of objects at runtime. Depending on the current value of obj, different types of members can be called, such as the Length property of a string, addition operation of an integer, and the Count property of a list.