Menu

Type casts

Will Pittenger

Overview

There are many times in which a variable is of one type, but you need another. So someone in the past invented the type cast. ASIL uses a constructor syntax for type casts. That means a type cast would look like a function call. However, type casts aren't constructors and they aren't declared as functions. (They do behave like a function though.) A type cast can be either implicit or explicit. If it's explicit, then the compiler has to be told to apply the type cast. Otherwise, it can do so without being told.

Type casting primitives

Sample type cast

var int i = int(5.5)

Predefined implicit type casts for primitive types

Many implicit type casts are implicit for primitive types that store numbers. Those include the ones listed below. All of these implicit type casts never lose accuracy. There are also implicit type casts for astring and achar as show below. Note: astring isn't a primitive, but is shown anyway.

Source type Destination type
astring string
achar char
int int64
int obyte
int float
int double
word int64
word obyte
word float
word double
byte int16
byte dbyte
byte int32
byte qbyte
byte int64
byte obyte
byte int
byte word
byte float
byte double
int8 int16
int8 dbyte
int8 int32
int8 qbyte
int8 int64
int8 obyte
int8 int
int8 word
int8 float
int8 double
dbyte word
dbyte int32
dbyte qbyte
dbyte int64
dbyte obyte
dbyte float
dbyte double
int16 int
int16 int32
int16 qbyte
int16 int64
int16 obyte
int16 float
int16 double
qbyte int64
qbyte obyte
qbyte double
int32 int64
int32 obyte
int32 double
obyte double
int64 double
float double

Predefined explicit primitive types

Most should be obvious. So this list shows only a two of the not so obvious.

Source Destination
achar byte
byte achar

Custom type cast procedures

When you declare a type cast, you aren't allowed to make it static. However, they can be virtual, abstract, or final. They can also be part of an interface. Each type cast must include either the explicit or implicit keywords. They also must list the destination type. Type casts are always public. Note they don't have an identifier. Typically, you'll call the constructor of the destination type using the new keyword. The source type is always the enclosing type. Use the return keyword to return the instance of the destination type.

[(\virtual\ | \abstract\ | \final\)] \typecast\ (\explicit\ | \implicit\) /TypeDescriptor/
  ' Return an instance of the desired type

For more on what /TypeDescriptor/ can be, see Type descriptors.


Related

Wiki: Appendices-Terms-Type descriptors
Wiki: Home
Wiki: Keywords
Wiki: keywords-abstract
Wiki: keywords-constructor
Wiki: keywords-explicit
Wiki: keywords-final
Wiki: keywords-implicit
Wiki: keywords-interface
Wiki: keywords-new
Wiki: keywords-public
Wiki: keywords-return
Wiki: keywords-typecast
Wiki: keywords-virtual