Skip to content

Latest commit

 

History

History
52 lines (35 loc) · 1.19 KB

File metadata and controls

52 lines (35 loc) · 1.19 KB

Type Transformation

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.

Transformation Contract

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();
}

as Keyword

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; 

Primitive Transformations

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;