Dynamic objects in C# 4.0 …and X++
C# 4.0 which recently has been released introduces a new static type with the name dynamic. The semantic of declaring a variable as dynamic is to defer all type checking from compile-time to run-time. This feature doesn’t enable new run-time capabilities, but it certainly makes your code more readable – especially when you interacting with not-strongly-typed languages, such as javascript or dynamic languages.
Consider this example in C#. The example uses reflection to invoke a named method – “Add” in this case. There is no enforcement at compile time, i.e. there is no guarantee that obj has an “Add” method that takes 2 ints as parameters and return an int. Further, which is the point of this discussion, the example contains quite a lot of glue code, which obscures the intention.
1: using System;2: using System.Reflection;3:4: class Class15: {6: static void Main(string[] args)7: {8: object obj = <some constructor>;9: object[] parameters = new object[] { 2, 5 };10: Type type = obj.GetType();11: int res = (int)type.InvokeMember("Add",12: BindingFlags.InvokeMethod, null, obj, parameters);13: Console.Write("Result: {0}", res);14: }14: }
Now, let us rewrite the example to use the dynamic type. Notice how the intention is crystal clear. You still don’t get compile-time checking – but hey, you didn’t have that before either.
1: using System;2:3: class Class14: {5: static void Main(string[] args)6: {7: dynamic obj = <some constructor>;8: int res = obj.Add(2, 5);9: Console.Write("Result: {0}", res);10: }11: }
There is, of course, much more to this feature in C#. For example, you are able to control how the runtime checking behaves, and how the late-bound invocation is implemented.
So far so good – but what does that have to do with X++? Well, X++ is a strongly typed language – like C#; and like in C# you sometimes need to call into weakly typed objects. In AX forms, reports and datasets are weakly typed (i.e. they are not known to the X++ type system). So since the very first version of AX we have had the challenge of bridging this gap – without ruining the code readability.
The interesting thing is that we in 1996 came up with the same solution to this problem, namely: Create a static type that instructs the compiler to relax all checks on operations on variables of the type. The C# solution is in many ways cleaner, more flexible and more robust – but the main principle of the solution is the same. You may already have guessed the X++ solution, but here it is: Types declared as object are not subject to compile time checking. This is of course an overloading of the object semantics – object is also the root base type of all classes.
Here is an X++ example, similar the C# examples above:
1: static void LateBindingJob(Args _args)2: {3: object obj = <some constructor>;4: int res = obj.Add(2, 5);5:6: info(strfmt("Result: %1", res));7: }
Call me a geek – but it makes me happy when the two languages converge.


