C# Keywords Tutorial Part 25: dynamic
Amr Saafan
Founder | CTO | Software Architect & Consultant | Engineering Manager | Project Manager | Product Owner | +27K Followers | Now Hiring!
C# is a potent programming language that provides developers with an array of features. One of these features is the “dynamic” keyword, which permits dynamic typing during runtime. This blog post will examine the “dynamic” keyword in C# and furnish some code examples to demonstrate its usage.
What is the “dynamic” keyword in C#?
When declaring a value in C# that will be dynamically written at runtime, the “dynamic” term is used. This implies that depending on the number that is given to the variable, its type will be decided at runtime. “Dynamic” variables are not needed to have a particular type given to them until runtime, in contrast to statically typed variables, which must have that type specified at compile time.
Using the “dynamic” keyword in C#
To use the “dynamic” keyword in C#, simply declare a variable using the keyword “dynamic” instead of a specific data type. Here’s an example:
dynamic dynamicVariable = 42;
Console.WriteLine(dynamicVariable.GetType().ToString()); // Output: System.Int32
dynamic dynamicVariable = "Hello, world!";
Console.WriteLine(dynamicVariable.GetType().ToString()); // Output: System.String
领英推荐
In the example above, we declare a variable “dynamicVariable” using the “dynamic” keyword and assign an integer value to it. We then use the “GetType()” method to determine the type of the variable at runtime and output the result to the console.
Next, we assign a string value to the same variable, and again use the “GetType()” method to output the type at runtime. As you can see, the type of the variable changes based on the value assigned to it.
Benefits of using the “dynamic” keyword in C#
Using the “dynamic” keyword in C# can provide some benefits, such as: