How to check type of an object to a class name?

Jonathan M Davis jmdavisProg at gmx.com
Mon Mar 5 17:21:07 PST 2012


On Tuesday, March 06, 2012 01:37:05 Chris Pons wrote:
> Is it possible to check the type of an object to a class name?
> 
> //Something like this:
> Class test
> {
> //...
> }
> 
> assert(is(anonObject == typeof(test))

If you want to check whether a particular object is of a particular type at 
runtime, then cast and check whether it's null. If you want to know the 
_exact_ type of an object, then use typeid.

class A
{}

class B : A
{}

class C : B
{}

void main()
{
 A obj = new C;
 assert(cast(A)obj);
 assert(cast(B)obj);
 assert(cast(C)obj);
 assert(typeid(obj) != typeid(A));
 assert(typeid(obj) != typeid(B));
 assert(typeid(obj) == typeid(C));
}

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list