Type Casting

Introduction

Type casting in Type-C allows for the conversion of values between different data types. This feature is particularly useful when you need to operate on a value with a type that is different from its current type or when passing values to functions that require a specific type. Type-C implements casting with the as keyword, which comes in three forms, each catering to different levels of safety and type assurance. it is important to keep in mind that type casting doesn't necessarily occur only when the programmer specifies it, any assignment (or argument passing etc) between a type and a structurally-different but compatible type results in casting-code generated by the compiler, under the hood. These casts are safe and predictable by the compiler through the inference engine and type tracking of expressions.

Regular Casting

Regular casting, performed with the as operator, is the standard method for type casting in Type-C. This form includes compiler checks to ensure the safety and validity of the cast. It's primarily used when converting between compatible types where the structure and size of the data align well.

Forced Type Casting

Forced casting, done using the as! operator, bypasses compiler checks. This type of casting is powerful but should be used with caution, as it can lead to undefined behavior if used improperly. It is most appropriate in situations where the developer has complete certainty about the underlying type and structure of the data, often following an explicit type check.

Safe Casting

Safe casting employs the as? operator and is the most cautious approach. If the cast is possible, it returns the value in the casted type; otherwise, it yields null. This method returns a nullable type, providing an additional safety layer by avoiding potential runtime errors from unsuccessful casts. Also, this casting works only data types which can be Nullable.

When it comes to converting between instances of classes/interface, where the casting is uncertain, using the safe casting as? is the best approach since it handles the check and the casting at the same time in the virtual machine, hence improving performance.

Type casting rules:

For forced casting, no rule is applied. It is a used it at your own risk feature. For regular casting, the following rules are applied:

  • t1 as t2, as an expression is allowed if t1 and t2, are of the same base type (both interfaces, or both primitives, etc).
  • t1 as t2, as a type is allowed if t1 and t2 are classes/interfaces or mixed.
  • t1 as t2, as a type is allowed if t1 and t2 are variants or variant constructors.

Kudos! Keep reading!