In the C# language, the dynamic keyword influences compilation. A dynamic variable can have any type. Its type can change during runtime.
The downside is that performance suffers and you lose compile-time checking. Dynamic is advanced functionality—it can be useful, but usually it should be avoided.
Dynamic is used to replace other types such as int
, bool
or string
. We assign the value 1 to the dynamic variable a. This means "a" is of type System.Int32
.
string
array. The type again changes. You can also use dynamic as a return type (or formal parameter type).static
field, and call a nonexistent property on it. This would not be possible without dynamic.using System;
class Program
{
static dynamic _y;
static void Main()
{
// Use dynamic local.
dynamic a = 1;
Console.WriteLine(a);
// Dynamic now has a different type.
a = new string[0];
Console.WriteLine(a);
// Assign to dynamic method result.
a = Test();
Console.WriteLine(a);
// Use dynamic field.
_y = "carrot";
// We can call anything on a dynamic variable.
// ... It may result in a runtime error.
Console.WriteLine(_y.Error);
}
static dynamic Test()
{
return 1;
}
}1
System.String[]
1
Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:
'string' does not contain a definition for 'Error'...
You won't find any "dynamic" types in the virtual
execution engine. Instead, the C# compile builds up an alternate representation of your dynamic code.
class
being generated by the compiler.static
class
is instantiated.[CompilerGenerated] private static class <Main>o__SiteContainer0 { // Fields public static CallSite<Action<CallSite, Type, object>> <>p__Site1; public static CallSite<Action<CallSite, Type, object>> <>p__Site2; public static CallSite<Action<CallSite, Type, object>> <>p__Site3; }if (<Main>o__SiteContainer0.<>p__Site1 == null) { <Main>o__SiteContainer0.<>p__Site1 = CallSite<Action<CallSite, Type, object>>.Create( Binder.InvokeMember(CSharpBinderFlags.ResultDiscarded, "WriteLine", null, typeof(Program), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create( CSharpArgumentInfoFlags.IsStaticType | CSharpArgumentInfoFlags.UseCompileTimeType, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); } <Main>o__SiteContainer0.<>p__Site1.Target(<Main>o__SiteContainer0.<>p__Site1, typeof(Console), a);
The dynamic keyword is used as a type in the C# language, but it is not a type in the underlying intermediate language. Thus, it can be considered a high-level type but not a low-level type.
params
keyword.It is definitely a bad idea to use dynamic in all cases where it can be used. This is because your programs will lose the benefits of compile-time checking and they will also be much slower.
The dynamic keyword provides access to a layer of functionality on top of the Common Language Runtime. Dynamic is implemented with a lot of inserted code.