InstanceOf

Timon Gehr timon.gehr at gmx.ch
Sun Jun 23 04:31:18 PDT 2013


On 06/23/2013 01:26 PM, Lemonfiend wrote:
>> foreach (I i; array) {
>>     if (B b = cast(B) i) { ... }
>> }
>
> Thanks all 3 of you for the quick and identical answers. :)
>
> It had not occurred to me to use a cast for this, but indeed the
> language ref says the same:
> "In order to determine if an object o is an instance of a class B use a
> cast"
>
> It does a bit inelegant to me.. Or are casts simply extremely cheap?
>
>

Casts are as cheap as testing whether an object is an instance of a 
certain class. Having the cast evaluate to a nullable reference is 
certainly more elegant than having instanceof and cast as separate 
constructs, where the cast may throw.


More information about the Digitalmars-d-learn mailing list