Home
Search
C# dynamic KeywordUse the dynamic keyword to specify a type is not known at compile-time. Inspect C# code and IL.
Dynamic. In the C# language, the dynamic keyword influences compilation. A dynamic variable can have any type. Its type can change during runtime.
A warning. 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.
Example. 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.
Int, uint
Next We assign it to a string array. The type again changes. You can also use dynamic as a return type (or formal parameter type).
Finally We use a dynamic static field, and call a nonexistent property on it. This would not be possible without dynamic.
Array
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'...
Nonexistent members. The compiler allows you to call nonexistent properties, fields and methods on dynamic. You can see that the "_y" is a string, but there is no Error property on String.
And With dynamic, this results in a run-time error. Without dynamic, we would get a compile-time error.
Code generated for above example, C#:
[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);
Internals. 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.
Il Looking at the IL, we see that the dynamic keyword results in a custom class being generated by the compiler.
Next We can look at the call sites themselves. At each call site, the site field from the above static class is instantiated.
Type. 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.
Note Most constructs in the C# language correspond fairly closely to their underlying representation.
Tip Other exceptions to this rule include the yield return construct and the params keyword.
Yield
Params
Uses. 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.
Note All the code generated by the C# compiler would yield a program that is many times slower than a regular C# program.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on 9/13/2022 (rewrite).
Home
© 2007-2022 sam allen.
see site info on the changelog.