In c#, dynamic type is a known variable once the program is executed. Dynamic types were introduced in C# 4.0 to improve interoperability with other dynamic languages and COM (Component Object Model).
The compiler does not check the type of a dynamic type variable at compile time, instead, the compiler gets the type at run time. A dynamic type variable is created using the keyword "dynamic". Let’s declare a dynamic type variable:
csharpdynamic value = 145;
In the above syntax, the value can take any data type, and the type will be evaluated when the program runs.
Dynamic types are useful when the type of data varies in different scenarios. For example, you can use them for objects returned from COM or DOM APIs, or objects obtained from dynamic languages.
Interacting with dynamic objects: Let’s consider a scenario where we interact with an external library that returns objects whose types are unknown at compile time.
csharpusing System; public class Program { public static void Main() { // Assigning a string to a dynamic variable dynamic value = "Hello, C#"; Console.WriteLine(value); // Output: Hello, C# // Now assigning an integer to the same dynamic variable value = 123; Console.WriteLine(value); // Output: 123 // Assigning an anonymous type value = new { Name = "Alice", Age = 25 }; Console.WriteLine($"Name: {value.Name}, Age: {value.Age}"); // Output: Name: Alice, Age: 25 } }
Output
In the above code, we are not getting the data type of the dynamic variable. We can use the GetType() method to get the actual type of a dynamic variable at runtime. Dynamic type changes its type at run time based on the value present on the right side. As shown in the example below.
Get the actual type of Dynamic variable: In this example, we use the GetType() method to get the type of the dynamic variable.
csharpusing System; class Gettype { static public void Main() { // Dynamic variables dynamic val1 = "letsupdateskills"; dynamic val2 = 101234; dynamic val3 = 1056.54; dynamic val4 = true; // Using GetType() method Console.WriteLine("Actual type of value1: {0}", val1.GetType().ToString()); Console.WriteLine("Actual type of value2: {0}", val2.GetType().ToString()); Console.WriteLine("Actual type of value3: {0}", val3.GetType().ToString()); Console.WriteLine("Actual type of value4: {0}", val4.GetType().ToString()); } }
Output
Copyrights © 2024 letsupdateskills All rights reserved