1: using System;
2:
3: namespace Example
4: {
5: public class Test1
6: {
7: public string strMyValue;
8: // public Test1()
9: // {
10: // Console.WriteLine("Test1 () Constructor");
11: // strMyValue = "Doh!";
12: // }
13: public Test1(string inMyValue)
14: {
15: Console.WriteLine(" Test1 ({0}) Constructor", inMyValue);
16: strMyValue = inMyValue;
17: }
18: ~Test1()
19: {
20: Console.WriteLine(" Test1 Finalize [{0}]", strMyValue);
21: }
22: }
23:
24: public class Test2 : Test1
25: {
26: //protected override void Finalize()
27: //
28: //I tried the above line and got a compiler error CS0249
29: // because ~Test2 is the required Finalize format for C#
30: // from the MSDN site:
31: //
32: // ~MyClass()
33: // {
34: // // Perform some cleanup operations here.
35: // }
36: //
37: // This code implicitly translates to the following.
38: //
39: // protected override void Finalize()
40: // {
41: // try
42: // {
43: // // Perform some cleanup operations here.
44: // }
45: // finally
46: // {
47: // base.Finalize();
48: // }
49: // }
50: public Test2(string x)
51: : base(x) // If you omit this line it will not compile
52: // unless you add a constructor for Test1 which
53: // takes no arguments. I have provided one, comment the
54: // base call out and then uncomment the Test1() above
55: // and take a look...I can wait...ok, see how it
56: // creates an underlying Type1 for the Test2? I didn't
57: // expect that.
58: {
59: Console.WriteLine(" Test2 ({0}) Constructor", x);
60: }
61: ~Test2()
62: {
63: Console.WriteLine(" Test2 Finalize [{0}]", strMyValue);
64: }
65: }
66:
67: public struct Test3
68: {
69: public string strMyValue;
70: public Test3(string inMyValue)
71: {
72: strMyValue = inMyValue;
73: }
74: //protected override void Finalize()
75: //see the note above
76: //
77: //but I still can't do the following because this isn't a class
78: // ~Test3()
79: // {
80: // Console.WriteLine("Test3 Finalize [{0}]", strMyValue);
81: // }
82: }
83:
84: public class MemoryExample
85: {
86: static public object objHolder; // defaults to null
87:
88: static void Main(string[] args)
89: {
90: object one;
91:
92: Console.WriteLine("BEGIN:");
93: Console.WriteLine(" Create a new Test1");
94: one = new Test1("blah");
95: Console.WriteLine(" Create a new Test2");
96: one = new Test2("foo");
97: Console.WriteLine(" Create a new Test3");
98: one = new Test3("barh");
99: one = null;
100: Console.WriteLine(" Start First Collection Point");
101: GC.Collect();
102: GC.WaitForPendingFinalizers();
103: Console.WriteLine(" End First Collection Point");
104: Console.WriteLine("END");
105: }
106: }
107:
108: }
109: