Casting
Casting is a process in which the data type of a variable or expression is explicitly converted to another type. Synergy DBL enables you to cast an object variable to a specific class type (including @class). You can also cast an integer value (for example, a Boolean) to or from an i4 variable (for example, an enumeration).
In Synergy .NET, to cast a negative number, the negative number must be in parentheses. For example, (@d)(-123). |
Casting supports upcasting (converting a derived class to a more general parent class) and downcasting (converting from a parent class to a more specific class). For example, in figure 1, you can cast c2 to c1 or object and vice versa, but you can’t cast c3 to c2 or c1.
|
The example below assumes ChildClass extends ParentClass and OtherClass doesn’t extend either class:
var1, @ParentClass var2, @ChildClass var3, @ChildClass var4, @ParentClass var5, @OtherClass var1 = new ParentClass() var2 = new ChildClass() var4 = (ParentClass)var2 ;Cast allowed but not necessary var3 = (ChildClass)var2 ;Cast allowed but not necessary var3 = (ChildClass)var1 ;Cast allowed (but if var1 contains an instance ; of a ParentClass object, fail at runtime) var5 = (OtherClass)var1 ;Invalid cast
To reference a member of the object that has been cast, you need to wrap the cast part of the path in parenthesis. Two examples of the syntax are shown below:
((parent_class)object_var).field ((parent_class)object_var).method()
The first example demonstrates how to access a field from an object variable that has been cast. The second shows how to call a method on a cast object variable.
If you get an “Invalid statement at or near {%s}” error (INVSTMT) or an “Invalid expression at or near {%s}” error (INVEXPR) for an expression in a complex statement that contains the cast of a path, try enclosing the full path in parentheses. For example, change if (boolean)al[1] then to if ((boolean)al[1]) then Without the parentheses, the parser interprets (boolean) as the condition in the IF statement and a1[1] as the statement to be executed after an implied THEN statement. The parentheses ensure that the full path (boolean)a1[1] is interpreted as the condition. |
To allow casting of objects to unrelated types, you must implement an op_Explicit operator in your class that has a return type to which you want to support conversion. op_Explicit cannot be invoked directly, only through casting. The following example uses op_Explicit to convert from i4 to myclass:
public static method op_Explicit, @myclass p1, i4 proc mreturn new myclass(p1) end
Each conversion method must have one parameter that designates the source of the conversion and a return type to denote the destination for the conversion.
Also see Conversion operators for user-defined explicit conversions for classes.