Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Getting dynamic runtime type information


The simplest form of reflection available in D is runtime type information, which is available through the typeid() operator. It is used extensively by the druntime implementation and is integral to the safe dynamic casting of classes.

How to do it…

Let's execute the following steps to get dynamic runtime type information:

  1. In most cases, you only need to write typeid(variable_or_type).

  2. If you want to get a dynamic class type through an interface, first cast it to Object, check for null, and then use typeid(the_casted_object).

The code is as follows:

TypeInfo typeInfoAboutInt = typeid(int);
typeInfoAboutInt = typeid(1); // also works

How it works…

The compiler and the runtime library automatically define type information for all types. This information is found in static TypeInfo objects, which is retrieved by reference using the typeid() operator. The definition of the TypeInfo interface is found in the automatically-imported object.d module of druntime,...