Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i test that an object is an instance of a particular class in D?

How do i test that an object is an instance of a particular class in D?

Something akin to Javascript's instanceof keyword?

like image 504
Gary Willoughby Avatar asked Jan 24 '12 21:01

Gary Willoughby


2 Answers

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);
like image 132
eco Avatar answered Oct 05 '22 00:10

eco


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) );
}
like image 37
Mihails Strasuns Avatar answered Oct 05 '22 02:10

Mihails Strasuns