Search⌘ K
AI Features

Dynamic Language Runtime

Explore how the Dynamic Language Runtime (DLR) allows C# to support dynamic typing and binding, enabling runtime discovery of object members, flexible property and method usage, and processing of unpredictable data like JSON. Understand the benefits and trade-offs of using dynamic features versus static typing in application development.

Although C# is primarily a statically-typed language, it supports dynamic features through the dynamic language runtime (DLR). To understand this feature, we should consider the difference between statically and dynamically-typed languages. In languages with static typing, the identification of all types and their members (such as properties and methods) occurs at the compilation stage.

Consider the following Course class:

C# 14.0
namespace DynamicLanguageRuntime;
public class Course
{
public string Title { get; set; } = string.Empty;
}

We have access to the Title property when we create an instance of the class. If we try to access a member that doesn’t exist, we get a compile-time error.

Next, we write a main program that attempts to access a non-existent property on this statically-typed object:

C# 14.0
using DynamicLanguageRuntime;
var course = new Course() { Title = ".NET Fundamentals" };
// Duration property does not exist
// We will get an error during compilation
Console.WriteLine(course.Duration);
  • Line 3: We create an instance of the class using the var keyword and set the Title property.

  • Line 7: We attempt to print the Duration property to the console, which triggers a compile-time error because the compiler verifies members beforehand.

In dynamically-typed languages, the runtime doesn’t know anything about the properties and methods of types until execution. With the help of the DLR, it’s ...