root/trunk/src/tutorials/examples/is_it_an_object/is_it_an_object.d

Revision 6, 2.3 kB (checked in by jcc7, 3 years ago)

Made more progress in developing convertToWiki and added some files.

Line 
1 /*
2     Author: J C Calvarese
3     License: Public Domain
4     Purpose: Determine whether an item is an object or not.
5 */
6
7 import std.stdio;
8
9
10 struct myStruct
11 {
12     int item1;
13     int item2;
14 }
15
16
17 class MyClass
18 {
19     int myInt1;
20     int myInt2;
21
22     this()
23     {
24         writefln("MyClass initialized.");
25     }
26 }
27
28
29 class MyOtherClass
30 {
31     double d1;
32
33     this()
34     {
35         writefln("MyOtherClass initialized.");
36     }
37 }
38
39 void main()
40 {
41     MyClass mc = new MyClass;
42     myStruct ms;
43     int someInt;
44
45     if(!(cast(Object)mc is null)) writefln("mc is an object (by casting)");
46     if(!(cast(MyClass)mc is null)) writefln("mc is a MyClass object (by casting)");
47     if(!(cast(MyOtherClass)mc is null)) writefln("mc is a MyOtherClass object (by casting)");
48     //if(!(cast(Object)ms is null)) writefln("ms is an object"); //error: cannot cast from myStruct to object.Object
49     //if(!(cast(Object)someInt is null)) writefln("someInt is an object"); //error: cannot cast from int to object.Object
50
51     if(typeid(typeof(mc)) == typeid(MyClass)) writefln("mc is a MyClass (by typeid)");
52     if(typeid(typeof(ms)) == typeid(MyClass)) writefln("ms is a MyClass (by typeid)");
53     if(typeid(typeof(someInt)) == typeid(MyClass)) writefln("someInt is a MyClass (by typeid)");
54
55     if(typeid(typeof(mc)) == typeid(MyOtherClass)) writefln("mc is a MyOtherClass (by typeid)"); /* Oops, I guess all objects have the same typeid */
56     if(typeid(typeof(ms)) == typeid(MyOtherClass)) writefln("ms is a MyOtherClass (by typeid)");
57     if(typeid(typeof(someInt)) == typeid(MyOtherClass)) writefln("someInt is a MyOtherClass (by typeid)");
58    
59
60     if(typeid(typeof(mc)) == typeid(Object)) writefln("mc is an object (by typeid)");
61     if(typeid(typeof(ms)) == typeid(Object)) writefln("ms is an object (by typeid)");
62     if(typeid(typeof(someInt)) == typeid(Object)) writefln("someInt is an object (by typeid)");
63
64     if(typeid(typeof(mc)) == typeid(myStruct)) writefln("mc is a myStruct (by typeid)");
65     if(typeid(typeof(ms)) == typeid(myStruct)) writefln("ms is a myStruct (by typeid)");
66     if(typeid(typeof(someInt)) == typeid(myStruct)) writefln("someInt is a myStruct (by typeid)");
67
68     if(typeid(typeof(mc)) == typeid(int)) writefln("mc is an int (by typeid)");
69     if(typeid(typeof(ms)) == typeid(int)) writefln("ms is an int (by typeid)");
70     if(typeid(typeof(someInt)) == typeid(int)) writefln("someInt is an int (by typeid)");
71 }
Note: See TracBrowser for help on using the browser.