10. What is C#?
Dynamic type was introduced with C# 4.0. Dynamic types are declared with the dynamic keyword. Dynamic types bypass compile-time type checking and these operations are resolved at run time. During compilation, dynamic is converted to System.Object and compiler will emit the code for type safety during runtime.
If the value provided to a dynamic variable is not valid, exception would be thrown at run time not at compile time.
class Program
{
public static void Main()
{
dynamic d = 1; //assigning integer
Console.WriteLine(d);
d = "Hi Dynamic"; //assigning string to the same variable d
Console.WriteLine(d);
d = TestData(); //assigning method result to the same variable d
Console.WriteLine(d);
// You can call anything on a dynamic variable,
// but it may result in a runtime error
Console.WriteLine(d.Error);
}
public static double TestData()
{
return 12.80;
}
}
/* Out Put
10
Hi Dynamic
12.80
RuntimeBinderException was unhandled, 'double' does not contain a definition for 'Error'
*/