dynamic (C# Reference)

The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time. The dynamic type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).

Type dynamic behaves like type object in most circumstances. However, operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time. As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.

The following example contrasts a variable of type dynamic to a variable of type object. To verify the type of each variable at compile time, place the mouse pointer over dyn or obj in the WriteLine statements. IntelliSense shows dynamic for dyn and object for obj.

A compiler error is reported for the attempted addition of an integer and an object in expression obj + 3. However, no error is reported for dyn + 3. The expression that contains dyn is not checked at compile time because the type of dyn is dynamic.

In any context where types serve as values, such as on the right side of an is operator or an as operator, or as the argument to typeof as part of a constructed type. For example, dynamic can be used in the following expressions.

int i = 8;
dynamic d;
// With the is operator. // The dynamic type behaves like object. The following // expression returns true unless someVar has the value null. if (someVar isdynamic) { }
// With the as operator.
d = i asdynamic;
// With typeof, as part of a constructed type.
Console.WriteLine(typeof(List<dynamic>));
// The following statement causes a compiler error. //Console.WriteLine(typeof(dynamic));