C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: Dynamic is advanced functionality. It can be useful. But usually it should be avoided.
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.
ArrayC# program that uses dynamic type
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;
}
}
Output
1
System.String[]
1
Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:
'string' does not contain a definition for 'Error'...
And: With dynamic, this results in a run-time error. Without dynamic, we would get a compile-time error.
Instead: You are calling something named WriteLine at runtime and passing it one argument.
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;
}
Info: The class we are calling (Console) is specified as a Type pointer with typeof.
Typeof, nameofCode generated at call sites: C#
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);
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.
YieldParamsNote: All the code generated by the C# compiler would yield a program that is many times slower than a regular C# program.
And: With dynamic, you can avoid a lot of annoying, explicit casting when using this assembly.
Excel