Cast

From D Wiki
Jump to: navigation, search

Casting class types

Casting to a class type T from a value can be achieved with the following:

cast(T) value

Casting will result in a null reference when the cast cannot be made. (There is no instanceof operator, because it is not needed.)

MyType castedValue = cast(MyType) someValue;

if (castedValue !is null)
{
    /* use the casted value */
}

For added safety, the following pattern can be used. This is safer because the casted value may only be used if it holds a valid MyType, where the pattern above would let you use castedValue even if it is null.

if (MyType castedValue = cast(MyType) someValue)
{
   /* use the casted value */
}