Difference between revisions of "Cast"
(Added a page just for this one feature of D, as part of my personal campaign to fill the wiki with easy to find information.) |
m |
||
(3 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
== Casting class types == | == Casting class types == | ||
− | Casting to a class type ''T'' | + | Casting to a class type ''T'' from a value can be achieved with the following: |
<syntaxhighlight lang="D">cast(T) value</syntaxhighlight> | <syntaxhighlight lang="D">cast(T) value</syntaxhighlight> | ||
Line 7: | Line 7: | ||
Casting will result in a null reference when the cast cannot be made. (There is no ''instanceof'' operator, because it is not needed.) | Casting will result in a null reference when the cast cannot be made. (There is no ''instanceof'' operator, because it is not needed.) | ||
− | <syntaxhighlight lang="D">MyType castedValue = cast(MyType) someValue; | + | <syntaxhighlight lang="D"> |
+ | MyType castedValue = cast(MyType) someValue; | ||
− | if (castedValue ! | + | if (castedValue !is null) |
{ | { | ||
/* use the casted value */ | /* use the casted value */ | ||
}</syntaxhighlight> | }</syntaxhighlight> | ||
+ | |||
+ | 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. | ||
+ | |||
+ | <syntaxhighlight lang="D"> | ||
+ | if (MyType castedValue = cast(MyType) someValue) | ||
+ | { | ||
+ | /* use the casted value */ | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | |||
+ | [[Category:Tutorials]] |
Latest revision as of 18:57, 8 September 2015
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 */
}