Chapter 19. Dynamic Programming

In Chapter 4, we explained how dynamic binding works in the C# language. In this chapter, we look briefly at the DLR, and then explore the following dynamic programming patterns:

  • Numeric type unification

  • Dynamic member overload resolution

  • Implementing dynamic objects

  • Interoperating with dynamic languages

Note

In Chapter 25, we’ll describe how dynamic can improve COM interoperability.

The types in this chapter live in the System.Dynamic namespace, except for CallSite<>, which lives in System.Runtime.CompilerServices.

The Dynamic Language Runtime

C# relies on the Dynamic Language Runtime (DLR) to perform dynamic binding.

Contrary to its name, the DLR is not a dynamic version of the CLR. Rather, it’s a library that sits atop the CLR—just like any other library such as System.Xml.dll. Its primary role is to provide runtime services to unify dynamic programming—in both statically and dynamically typed languages. This means that languages such as C#, VB, IronPython, and IronRuby all use a common protocol for calling functions dynamically, allowing them to share libraries and call code written in other languages.

The DLR also makes it relatively easy to write new dynamic languages in .NET. Instead of having to emit IL, dynamic language authors work at the level of expression trees (the same expression trees in System.Linq.Expressions that we talked about in Chapter 8).

The DLR further ensures that all consumers get the benefit of call-site caching, an optimization whereby ...

Get C# 4.0 in a Nutshell, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.