/// compile with dmd -safe safetest.d module safetest; struct X { int x; } struct Y { float y; } class A {} class B : A {} class C {} void main() { /// POD cast X x = X(5); Y y = cast(Y)x; /// type conversion cast - works like an intrinsic function float f = -5.7f; assert(cast(int)f == -5); /// magic! the compiler turned the float to an int by taking the integer part float[] fa = [1.2, 2.3, 3.4]; auto ia = cast(int[])fa; // assert(ia[0]==1); /// the magic vanishes when dealing with arrays - this might appear unexpected/inconsistent to new users /// dynamic_cast behavior A a = new B; assert(a !is null); B b = cast(B)a; assert(b !is null); C c = cast(C)a; assert(c is null); /// more magic! the compiler will look at the class's RTTI to see if we can safely downcast // c = *cast(C*)(&a); /// this seems to be the only way to do an unsafe (zero-overhead) cast - /// take the reference's pointer, cast that then dereference that - /// quite ugly and the object reference must be in a variable /// (doesn't work in safe mode, obviously) auto aa = cast(A[])fa; /// perfectly valid code, even with -safe //delete aa[0]; /// this will cause an access violation /// notice that we can cast arrays of ints to classes to generate fake pointers, and "break" -safe }