On Sunday, 23 June 2013 at 15:15:16 UTC, Jacob Carlborg wrote:
On 2013-06-23 13:26, 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?

You can do something like this as well:

if (i.classinfo is B.classinfo) { }

But doing the cast is more efficient if you want to use the object of as the type you're checking for.

Using the .classinfo is what I looked at before asking here.
However, according to the specs:
".classinfo applied to an interface gives the information for the interface, not the class it might be an instance of."
So the i.classinfo and B.classinfo would be different?

You can also hide the cast in a function if you want to be a bit more clear of the intent:

T instanceOf (T) (Object value)
{
    return cast(T) value);
}

if (i.instanceOf!(B)) { }

This is indeed what I did :)

Reply via email to