Dynamic (id)

The Dynamic type can be used for fields, variables or parameters whose concrete type is not known at compile time.

In Oxygene, C#, Swift and Mercury, the dynamic keyword can also be used to refer to this type.

Different than Object, which is the base type of all types and where a variable typed as Object provides the most strict access to only members known to be defined on the base Object class itself, a variable typed as Dynamic allows code to try and access any known (or even unknown) method or property, without any compile time checks. Only at runtime does the call get validated (and will fail, if the requested method or property does not exist).

On the Cocoa platform, the dynamic can also be referred to as id, and behaves identically to the id type provided by Objective-C or the Any and AnyObject types provided by Apple Swift.

When using the Swift language with Elements, both Any and AnyObject are aliases for dynamic.

Typical uses of Dynamic include:

  • Working with COM/IDispatch objects on .NET or Island/Windows.
  • Working with JavaScript objects on Island/WebAssembly.
  • Working with Cocoa APIs that use id.

Constrained Dynamics (kindof)

Constrained Dynamics can be thought of as a "best of both worlds" combination of a strongly typed varible and a dynamic.

A strongly-typed variable enforces the strictest compiler checks possible: it only allows calls the the exact set of members knows to exist. A Dynamic variable, on the flip side, has no checks at all; the compiler will allow any call, valid or not.

A Constrained Dynamic sits in the middle. It has a known base type (e.g. Element) and will nit allow arbitrary calls. But, it will allow calls to any descendant type.

Constrained Dynamic are declared using the standard generics syntax:

var c: dynamic<Control> := new Button;
dynamic<Control> c = new Button();
let c: dynamic<Control> = Button()
Dim c As dynamic(Of Control) = new Button()

In the example above, c is Dynamic, but constrained to types descending from Control. In this case, the instance contains a Button. The compiler will allow calls on c to known members of any subclass of Control, say the Click event of a button or the Text property of Label. But it will not allow calls to arbitrary unknown members, or members only known from classes that do not descend from Control.

On the Cocoa platform, Constrained Dynamics behave identically to the __kindof types provided by Objective-C.

Typical uses of Dynamic include:

  • Working with Cocoa APIs that use __kindof.

See Also