www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - instanceof?

reply "Maxime Chevalier" <maximechevalierb gmail.com> writes:
Getting started with D. I've been doing alot of googling trying 
to find out what's the best way to check if an object is an 
instance of some class. So far, I found you could do:

if (typeid(obj) == typeid(Class)) doSomething();

or:

if (cast(Class)obj) doSomething();

These both seem a little clumsy, however. Is there a better way 
to do this?
Aug 01 2012
next sibling parent "Adam D. Ruppe" <destructionator gmail.com> writes:
On Thursday, 2 August 2012 at 01:59:02 UTC, Maxime Chevalier 
wrote:
 These both seem a little clumsy, however. Is there a better way 
 to do this?

I don't know if it is the best way, but I use the cast myself, though I like using a little wrapper: T instanceof(T)(Object o) if(is(T == class)) { return cast(T) o; } Then, you can say if(object.instanceof!SomeClass) { // use } or if(auto some_class = object.instanceof!SomeClass) { // use some_class }
Aug 01 2012
prev sibling parent reply Jonathan M Davis <jmdavisProg gmx.com> writes:
On Thursday, August 02, 2012 03:59:01 Maxime Chevalier wrote:
 Getting started with D. I've been doing alot of googling trying
 to find out what's the best way to check if an object is an
 instance of some class. So far, I found you could do:
 
 if (typeid(obj) == typeid(Class)) doSomething();
 
 or:
 
 if (cast(Class)obj) doSomething();
 
 These both seem a little clumsy, however. Is there a better way
 to do this?

if(cast(Class)obj) is the canonical way to do it. - Jonathan M Davis
Aug 01 2012
parent Jacob Carlborg <doob me.com> writes:
On 2012-08-02 05:06, Jonathan M Davis wrote:

 if(cast(Class)obj)

 is the canonical way to do it.

Or, to use the value after the cast: if (auto foo = cast(Class) obj) // use foo -- /Jacob Carlborg
Aug 01 2012