GOTCHA #37 Rules to invoke base.Finalize() aren't consistentObject.Finalize() is an odd method. It is defined as protected overridable. As mentioned in the introduction to this chapter, in C# you implement your class's Finalize() method with the special syntax ~NameOfClass, where NameOfClass is the actual name of your class. This pseudo-destructor is compiled into the Finalize() method during the MSIL translation. Furthermore, within the C# destructor, you should not attempt to call Finalize() on the base class. The compiler-generated Finalize() takes care of calling the base class's Finalize(), even if an exception is raised, because the call is safe inside a finally block. For example, look at this pseudo-destructor: ~MyClass() { // Whatever cleanup code you write } The C# compiler will translate this into the Finalize() method in your assembly. A look at the generated MSIL using ildasm.exe will clarify this for you (see Figure 5-5). Figure 5-5. MSIL translation of a C# pseudo-destructorIf a C# programmer ever has to work with VB.NET code, he should remember that the rules are different. In VB.NET, you write Finalize() as a Protected Overrides method, and you must call MyBase.Finalize(), as shown in Example 5-4. Example 5-4. Writing Finalize() in VB.NETProtected Overrides Sub Finalize() Try 'Whatever cleanup code you write Finally MyBase.Finalize() End Try End Sub However, if you use the Dispose design pattern (refer to Gotcha #40, "Implementing IDisposable isn't enough"), then you most likely will not implement the Finalize() method in your derived classes. IN A NUTSHELLIn C#, do not invoke the base class's Finalize() method from within the destructor. In VB.NET, do invoke the base class's Finalize() method from within the Finalize() method. SEE ALSOGotcha #35, "Writing Finalize( ) is rarely a good idea," Gotcha #36, "Releasing managed resources in Finalize( ) can wreak havoc," Gotcha #38, "Depending on Finalize() can tie up critical resources," Gotcha #39, "Using Finalize() on disposed objects is costly," Gotcha #40, "Implementing IDisposable isn't enough," and Gotcha #41, "Using the Dispose Design Pattern doesn't guarantee cleanup." |