dynamic

suggest change

The dynamic keyword is used with dynamically typed objects. Objects declared as dynamic forego compile-time static checks, and are instead evaluated at runtime.

using System;
using System.Dynamic;

dynamic info = new ExpandoObject();
info.Id = 123;
info.Another = 456;

Console.WriteLine(info.Another);
// 456

Console.WriteLine(info.DoesntExist);
// Throws RuntimeBinderException

The following example uses dynamic with Newtonsoft’s library Json.NET, in order to easily read data from a deserialized JSON file.

try
{
    string json = @"{ x : 10, y : ""ho""}";
    dynamic deserializedJson = JsonConvert.DeserializeObject(json);
    int x = deserializedJson.x;
    string y = deserializedJson.y;
    // int z = deserializedJson.z; // throws RuntimeBinderException
}
catch (RuntimeBinderException e)
{
    // This exception is thrown when a property
    // that wasn't assigned to a dynamic variable is used
}

There are some limitations associated with the dynamic keyword. One of them is the use of extension methods. The following example adds an extension method for string: SayHello.

static class StringExtensions
{
    public static string SayHello(this string s) => $"Hello {s}!";
}

The first approach will be to call it as usual (as for a string):

var person = "Person";
Console.WriteLine(person.SayHello());

dynamic manager = "Manager";
Console.WriteLine(manager.SayHello()); // RuntimeBinderException

No compilation error, but at runtime you get a RuntimeBinderException. The workaround for this will be to call the extension method via the static class:

var helloManager = StringExtensions.SayHello(manager);
Console.WriteLine(helloManager);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Keywords:
* as
* goto
* break
* const
* for
* is
* fixed
* sealed
* typeof
* this
* dynamic
* void
* char
* params
* base
* string
* null
* return
* while
* using
* ulong
* uint
* unsafe
* int
* var
* lock
* where
* extern
* switch
* when
* struct
* static
* do
* bool
* long
* sizeof
* in
* enum
* ushort
* sbyte
* event

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
51 Keywords
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script