Tuesday 1 March 2016

Casting AX7

The previous version of X++ was very permissive in its treatment of type casting. Both up-casting and down-casting were allowed without intervention from the programmer. Some of the casting permitted in legacy X++ can’t be implemented in the confines of the .NET runtime environment.
In object oriented programming languages, including X++, casting refers to assignments between variables whose declared types are both in the same inheritance chain. A cast is either a down-cast or an up-cast. To set the stage for this discussion, we introduce a few self-explanatory class hierarchies:
Casting_DebugFeatures
As you can see, the MotorVehicle class isn’t related to the Animal cast.
An up-cast happens when assigning an expression of a derived type to a base type:
  Animal a = new Horse();
down-cast happens when assigning an expression of a base type to a derived variable.
Horse h = new Animal();
Both up-casts and down-casts are supported in X++. However, down-casts are dangerous and should be avoided whenever possible. The example above will fail with an InvalidCastException at runtime, since the assignment doesn’t make sense.
X++ supports late binding on a handful of types, like object and formrun. This means that the compiler won’t diagnose any errors at compile-time when it sees a method being called on those types, if that method isn’t declared explicitly on the type,. It’s assumed that the developer knows what they’re doing.
For instance, the following code may be found in a form.
Object o = element.args().caller();
  o.MyMethod(3.14, “Banana”);
The compiler can’t check the parameters, return values, etc. for the MyMethod method, since this method isn’t declared on the object class. At runtime, the call will be made using reflection, which is orders of magnitude slower than normal calls. note that calls to methods that are actually defined on the late binding types will be naturally checked.
For example, the call to ToString():
o.ToString(45);
will cause a compilation error:
'Object.toString' expects 0 argument(s), but 1 specified.
because the ToString method is defined on the object class.
There’s one difference from the implementation of previous version of X++, related to the fact that methods could be called on unrelated objects, as long as the name of the method was correct, even if the parameter profiles weren’t entirely correct. This isn’t supported in CIL.

Example

public class MyClass2
{
  public static void Main(Args a)
  {
    Object obj = new Car();
    Horse horse = obj; // exception now thrown
    horse.run();    // Used to call car.run()!
  }
}
You should use the IS and AS operators liberally in your code. The IS operator can be used if the expression provided is of a particular type (including derived types); the AS operator will perform casting into the given type and return null if a cast isn’t possible.

No comments:

Post a Comment