Adding Finalizers


Finalizers are functions that trigger when the .NET Framework recognizes that the program no longer needs the object. Whenever you create an instance of a class, the resulting object consumes a little bit of memory. The more objects you create, the more memory is consumed. The .NET Framework uses garbage collection to reclaim this memory. It identifies when objects are no longer needed and removes them from memory. A finalizer is a function that executes before the memory is reclaimed. You should add finalizers sparingly, and only when absolutely necessary, as they can significantly decrease the performance of your application.

To add a finalizer:

  1. Add a function without a return type. Name the function the same as the class name with a tilde symbol in front of the name .

  2. Don't add parameters to the function ( Figure 6.13 ).

    Figure 6.13 If you have used C++, you may be tempted to call ~Account a destructor; however, in C# this is called a Finalizer. Destructors in C++ are always guaranteed to execute. In C# finalizers are not guaranteed to get called, and sometimes they may get called more than once. They are mostly used to clean up operating system resources.
     class Account {    int Balance;  ~Account()   {   //clean OS resource   }  } 

graphics/tick.gif Tips

  • Classes can only have one finalizer.

  • In C#, the finalizer function also calls the finalizer function of the base class if there is one.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net