What is dynamic type in C#? How it is different from object?

C# 4.0 introduced a new type, dynamic. The type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like type object. At compile time, an element that is typed as dynamic is assumed to support any operation. Therefore, you do not have to be concerned about where the object gets its value from. However, if the code is not valid, errors are caught at run time.

Programming languages divide into languages with static typing and the ones with dynamic typing. Static typing means the type of a variable is known at compile time and dynamic typing means the type of a variable is interpreted at runtime. C# is statically typed and such tool as dynamic might confuse you at first. Though dynamic provides ability to write code which behaves as dynamically typed and interoperates with truelly dynamic languages, C# still stays statically, strongly typed (type can't be changed once interpreted) language.

In fact, dynamic is just an wrapper for System.Object with additional metadata needed for dynamic binding. 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.

So, the main difference between object and dynamic – with dynamic you tell the compiler that the type of an object can be known only at run time, and the compiler doesn’t try to interfere. As a result, you can write less code. In other aspects, there is not much difference from the behavior you get with the object keyword.

Short answer

  • dynamic type was introduced in C# 4.0.
  • At compile time, an element that is typed as dynamic is assumed to support any operation.
  • After compilation dynamic translates into object type and at run time behaves like object.