Introduction
Dynamic is a new type introduced in C# 4. It's a static type, but unlike other static types, the (potential) members of a dynamic object is not checked by the compiler. In most circumstances, it behaves as if it were an object. A dynamically typed element is assumed to support any action at compile time. The compiler does not check the type of the dynamic type variable at compile time, instead, the type is obtained at run time. The dynamic keyword is used to construct the dynamic type variable.
Example: dynamic Variable
dynamic MyDynamicVar = 1;
Recommended Topic, Palindrome in C#, singleton design pattern in c#, and Ienumerable vs Iqueryable.
Declaration of Dynamic Variable
The dynamic keyword enables you to use variables that are not type-specific and instead act as the type of data they contain. You may easily assign a new value to a dynamic variable, and if the type of value you're assigning isn't the same as the one it already has, the dynamic variable will immediately change the type. When we declare a variable dynamic, we're effectively telling the compiler to disable compile-time type checks. Dynamic is basically System. Object type under the hood, however, it is not necessary to cast a value before using it. Let's see this with an example.
// C# code to explain how to get the dynamic type variable's actual type.
using System;
class CodingNinjas{
// Main Method
static public void Main()
{
// Dynamic variables
dynamic value = true;
Console.WriteLine("Type of value: {0}", value.GetType().ToString());
value = 189234;
Console.WriteLine("Type of value: {0}", value.GetType().ToString());
value = 8952.58;
Console.WriteLine("Type of value: {0}", value.GetType().ToString());
value = "CODINGNINJAS";
Console.WriteLine("Type of value: {0}",value.GetType().ToString());
}
}
Output
Type of value: system. Boolean
type of value: system. Int32
type of value: system. Double
type of value: system. String
In the above example, there is one variable that is of dynamic type, and it takes all types of values such as int, bool, string, etc