Dynamic Type Binding - ablealias/MVC GitHub Wiki

In Dynamic binding, the compiler doesn't do any type checking at compile time. It simply assumes that the code is valid, no matter which members it tries to access the expression. All the checking is done at runtime, and an exception is thrown if the requested member doesn't exist on the expression.

Dynamic binding is an important feature of dynamically-typed languages such as Javascript. Although C# is primarily considered a statically-typed language with a high level of type safety, it also supports dynamic binding since version 4.

The core of dynamic binding support in C# is the dynamic keyword. With it, the variables can be declared to be dynamically-typed. For expressions involving such variables, static type checking at compile time is completely disabled, as in the following example,

dynamic text = "String value";
var textLength = text.Length;
var lengthString = text.Length.ToString();
var textMonth = text.Month; // compiles but throws exception at
runtime
dynamic date = DateTime.Now;
var dateLength = date.Length; // compiles but throws exception at
runtime
var dateMonth = date.Month; 

In the above example, using the dynamic keyword doesn’t make much sense. Of course, there are better use cases for the dynamic keyword, otherwise it wouldn’t have been added to the language.

For example, it can circumvent the restriction that anonymous types can only be used within a single method. Their type name can’t be declared as the return value of a method because it is visible only to the compiler. If the method is declared with a dynamic return value, the compiler will allow it to return a value of an anonymous type, for example,

public dynamic GetAnonymousType()
{
return new
{
Name = "John",
Surname = "Doe",
Age = 42
};
}

Of course, the returned value can be used outside the method, with the disadvantage that no IntelliSense or compile time type checking will be available for it as neither the compiler nor the editor is aware of the actual type being returned:

dynamic value = GetAnonymousType();
Console.WriteLine($"{value.Name} {value.Surname}, {value.Age}");

A great example of how much value dynamic binding can add when used correctly is the JSON.NET library for serializing and deserializing JSON. It can be best explained with the following example:

string json = @"
{
""name"": ""John"",
""surname"": ""Doe"",
""age"": 42
}";
dynamic value = JObject.Parse(json);
Console.WriteLine($"{value.name} {value.surname}, {value.age}");