How do i test that an object is an instance of a particular class in D?
Something akin to Javascript's instanceof
keyword?
Use cast
. It returns a null reference when you attempt to cast to a subclass it isn't an instance of (like C++'s dynamic_cast).
auto a = new Base;
auto b = cast(Child) a;
assert(b is null);
a = new Child;
auto c = cast(Child) a;
assert(c !is null);
typeid expression can tell you if instance is of some exact type (without considering inheritance hierarchy):
class A {}
class B : A {}
void main()
{
A a = new B();
// dynamic
assert( typeid(a) == typeid(B) );
// static
assert( typeid(typeof(a)) == typeid(A) );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With