Last update March 7, 2012

How To /
Realtime Type Information

Runtime Type Information (RTTI)

RTTI is one of those things that should be avoided where possible but you just can't live without sometimes. Note that at present the only information from digital mars about RTTI in D is in the object.d file. This may be because Walter plans to make the RTTI more powerful (see What Walter Said).

Determining the type of a object

To determine if an object is of a particular type simply cast (dynamic cast) it like so:

	cast(class) object
Null will be the result if the class type is not compatible with the object.


	B b = cast(B) a;

if ( b ) { printf("a is of type B"); }

Getting the class name of a object

To provide this kinda RTTI support in D all classes inherit Object (which can be found in dmd\src\phobos\object.d). To get the name of an object use


class A {}

int main ( char [] [] args ) {

	A a = new A;

return 1;


What Walter Said

Walter Said " I do intend to expand the 'classinfo' so that one could figure out all the fields and methods of a class. However, I spent some time trying to figure out how to make dynamic class loading work with some special compiler magic, but it isn't going to happen. The stumbling block is not knowing at compile time what the type of an expression is.

I could wave the magic spec wand and say that all methods in a dynamic class must return void and that data fields are not possible, but such restrictions make it not so useful. "


Runtime reflection for D


Please edit this howto with the reasons for + against RTTI and more forms of RTTI in D.

FrontPage | News | TestPage | MessageBoard | Search | Contributors | Folders | Index | Help | Preferences | Edit

Edit text of this page (date of last change: March 7, 2012 20:39 (diff))