| |
| Posted by Arafel in reply to IchorDev | PermalinkReply |
|
Arafel
Posted in reply to IchorDev
| On 10/8/23 7:59, IchorDev wrote:
> A common pattern when working with inheriting classes or classes that implement an interface is to use the base class or interface as a generic type:
> ```
> interface Thing{}
> class OtherThing: Thing{}
>
> Thing[] array = [new OtherThing(), …];
> ```
> So how do people usually check if an item in `array` is a sub-class of `Thing`, or implements an interface that inherited from `Thing`? Is `typeid` the only way to do this?
I faced this issue recently. In my case, and I think it's the most common case, I didn't care what exact type it was, I just wanted to make sure it was `OtherThing`. If it wasn't, the exact type didn't really matter.
If that's also your case, you can just cast to the type you need, and check for `null`. My case was like this:
```d
interface Thing{
void foo(Thing[] array);
}
class OtherThing: Thing{
override void foo(Thing[] array) {
foreach (thing; array) {
auto otherThing = cast (OtherThing) thing;
assert(otherThing, "Wrong type in `array`: " ~ typeid(thing).toString);
// Do something here
}
}
}
```
|