using System.IO; class Finalization1 { private StreamWriter _sw = null; public Finalization1() { _sw = new StreamWriter("Test.txt"); } ~Finalization1() { _sw.Close(); } } using System; using System.IO; public class Starter { public static Finalization2 Obj; public static void Main() { Obj = new Finalization2(); Obj.TimeStamp(); Obj = null; GC.Collect(); GC.WaitForPendingFinalizers(); // Obj has been resurrected but the following line will // cause an exception - stream writer was cleaned up // when destructor ran. Obj.TimeStamp(); } } public class Finalization2 { static private StreamWriter _sw = null; public Finalization2() { _sw = new StreamWriter("Test.txt"); } public void TimeStamp() { _sw.WriteLine(DateTime.Now.ToLongTimeString()); } ~Finalization2() { Starter.Obj = this; _sw.Close(); _sw = null; } } using System; using System.IO; public class Starter { public static Finalization2 Obj; public static void Main() { Obj = new Finalization2(); Obj.TimeStamp(); Obj = null; GC.Collect(); GC.WaitForPendingFinalizers(); // Obj has been resurrected and this time will not fail. Obj.TimeStamp(); } } public class Finalization2 { static private StreamWriter _sw = null; public Finalization2() { _sw = new StreamWriter("Test.txt"); } public void TimeStamp() { if (_sw == null) { _sw = new StreamWriter("Test.txt", true); } _sw.WriteLine(DateTime.Now.ToLongTimeString()); _sw.Flush(); } ~Finalization2() { // Do not want to re-register object if CLR is shutting // down. if (!Environment.HasShutdownStarted) { Starter.Obj = this; _sw.Close(); _sw = null; GC.ReRegisterForFinalize(this); } } } using System; using System.IO; public class Starter { public static void Main() { try { Finalization3 obj = null; obj = new Finalization3(); if (obj != null) { obj.MethodA(); } } catch (Exception xcp) { Console.WriteLine(xcp.Message); } Console.WriteLine("Press any key to continue..."); Console.Read(); } } public class Finalization3 { private bool _partialInitialization = false; public Finalization3() { try { Console.WriteLine("Finalization3 Constructor"); throw new Exception("Error"); } catch { GC.SuppressFinalize(this); _partialInitialization = true; } } public void MethodA() { if (_partialInitialization) { throw new Exception("Partial construction error"); } Console.WriteLine("Finalization3.MethodA"); } ~Finalization3() { Console.WriteLine("Finalization3 Destructor"); } }