In C*, casting is strictly a transformation, not a memory reinterpretation.
To convert one type to another, the source type must explicitly implement a transformation rule.
Transformations never happen implicitly. You must always use the as keyword to trigger a transformation or directly call Transform.
Type transformation is governed by the Transformable<T> contract, where T is the target type.
This contract defines how an instance of one type is consumed to produce an instance of another.
contract Transformable<T>
{
T Transform();
}The as keyword is the syntactic sugar for calling the Transformable<T>.Transform() method.
struct Vector : Transformable<int>
{
public int X;
public int Y;
public int Transform()
{
return X + Y;
}
}
var vec = new Vector(10, 20);
var length = vec as int; Even for primitive types, transformations are explicit.
However, for performance, the compiler optimizes primitive-to-primitive transformations into native machine instructions.
int small = 100;
var big = small as long;