Type conversion: Object runtime cast

The object runtime cast operator is used to check whether an object does descend from a particular class. Once the ancestry of the object is verified, the object can be accessed safely.

Syntax

(unit‑name::class‑name)object‑operand

Discussion

Due to the polymorphic nature of objects, the Chora compiler can’t always predict, which class the object used in an expression will have at the runtime. Especially the operands of the generic object data type can represent every object of any class defined in the project. From this arises the problem, that expressions involving members (properties, methods, etc.) of such objects can't be verified at the compilation time and no safe code can be generated to access them.

The object runtime cast operator is a special variant of type conversion suited to verify dynamically whether the class of the given object operand is equal to or it is derived from the class specified in the operator. If successful, the operator returns the original object interpreted as an instance of the specified class. Now, the members of the object can be accessed safely. If the verification fails, the operator returns a null object.

The desired destination class is specified between a pair of (...) (parentheses) composed of the unit name, the corresponding class is defined inside, and the name of the class itself, both separated by :: (double colon) signs. In the following example, the object runtime cast operator is used to verify whether the generic object operand o does refer to a Text or an Image view. In the case the verification succeeds, the view can be accessed:

var object o;

// Depending on the random value, the variable 'o' will
// refer to a 'Text' or 'Image' view.
if ( math_rand( 0, 100 ) > 50 )
  o = new Views::Text;
else
  o = new Views::Image;

// What kind of object is 'o'? Try to cast 'o' to 'Views::Text'
var Views::Text tv = (Views::Text)o;

// If the object is a 'Text' view, the 'Text' view specific
// properties can be accessed
if ( tv != null )
{
  tv.Font   = Resources::FontMedium;
  tv.String = "Hello word!";
}

// Is it possible to cast 'o' to 'Views::Image' class?
var Views::Image iv = (Views::Image)o;

// If the object is an 'Image' view, the 'Image' view 
// specific properties can be accessed.
if ( iv != null )
  iv.Bitmap = Resources::DefaultBitmap;

classof operator

The class of an object operand can also be verified by using the classof operator and the class runtime cast operator.