Home > Articles

This chapter is from the book

Creating Destructors and Handling Garbage Collection

The flip side of constructors are destructors, which are called when it's time to get rid of an object and perform cleanup, such as disconnecting from the Internet or closing files. Getting rid of no-longer-needed objects involves the C# garbage collector, which calls your destructor. The C# garbage collector is far more sophisticated than the ones available in most C++ implementations, as we'll see soon. Let's start with destructors first.

Creating a Destructor

You place the code you want to use to clean up an object when it's being deleted, if any, in a destructor. Destructors cannot be static, cannot be inherited, do not take parameters, and do not use access modifiers. They're declared much like constructors, except that their name is prefaced with a tilda (~). You can see an example in ch03_10.cs, which appears in Listing 3.10, and includes a destructor for the Customer class. When there are no more references to objects of this class in your code, the garbage collector is notified and will call the object's destructor (sooner or later—you can't predict when it will happen).

Listing 3.10 Creating a Destructor (ch03_10.cs)

class ch03_10
{
 static void Main()
 {
  Customer customer = new Customer();
 }
}

public class Customer
{
 public Customer()
 {
  System.Console.WriteLine("In Customer's constructor.");
 }

 ~Customer()
 {
  System.Console.WriteLine("In Customer's destructor.");
 }
}

Here's what you see when you run ch03_10.cs:

C:\>ch03_10
In Customer's constructor.
In Customer's destructor.

In C#, destructors are converted into a call to the System.Object class's Finalize method (which you cannot call directly in C#). In other words, this destructor:

~Customer()
{
 // Your code
}

is actually translated into this code by C# (the call to base.Finalize calls the Finalize method in the class the current class is based on; more on the base keyword in the next chapter):

protected override void Finalize()
{
 try
 {
  // Your code
 }
 finally
 {
  base.Finalize();
 }
}

However, in C#, you must use the standard destructor syntax as we've done in Listing 3.10, and not call or use the Finalize method directly.

Understanding Garbage Collection

Destructors are actually called by the C# garbage collector, which manages memory for you in C# code. When you create new objects with the new keyword in C++, you should also later use the delete keyword to delete those objects and free up their allocated memory. That's no longer necessary in C#—the garbage collector deletes objects no longer referenced in your code automatically (at a time of its choosing).

For C++ Programmers

In C#, you no longer have to use delete to explicitly delete objects after allocating them with new. The garbage collector will delete objects for you by itself. In fact, delete is not even a keyword in C#.

What that means in practical terms is that you don't have to worry about standard objects in your code as far as memory usage goes. On the other hand, when you use "unmanaged" resources like windows, files, or network connections, you should write a destructor that can be called by the garbage collector, and put the code you want to use to close or deallocate those resources in the destructor (because the garbage collector won't know how to do that itself).

Implementing a Dispose Method

On some occasions, you might want to do more than simply put code in a destructor to clean up resources. You might want to disconnect from the Internet or close a file as soon as you no longer need those resources. For such cases, C# recommends that you create a Dispose method. Because that method is public, your code can call it directly to dispose of the object that works with important resources you want to close.

For C++ Programmers

In C#, you can implement a Dispose method to explicitly deallocate resources.

In a Dispose method, you clean up after an object yourself, without C#'s help. Dispose can be called both explicitly, and/or by the code in your destructor. Note that if you call the Dispose method yourself, you should suppress garbage collection on the object once it's gone, as we'll do here.

Let's take a look at an example to see how this works. The Dispose method is formalized in C# as part of the IDisposable interface (we'll discuss interfaces in the next chapter). That has no real meaning for our code, except that we will indicate we're implementing the IDisposable interface. In our example, the Dispose method will clean up an object of a class we'll call Worker.

Note that if you call Dispose explicitly, you can access other objects from inside that method; however, you can't do so if Dispose is called from the destructor, because those objects might already have been destroyed. For that reason, we'll track whether Dispose is being called explicitly or by the destructor by passing Dispose a bool variable (set to true if we call Dispose, and false if the destructor calls Dispose). If that bool is true, we can access other objects in Dispose—otherwise, we can't.

Also, if the object is disposed of by calling the Dispose method, we don't want the garbage collector to try to dispose of it as well, which means we'll call the System.GC.SuppressFinalize method to make sure the garbage collector suppresses garbage collection for the object. You can see what this code looks like in ch03.11.cs, Listing 3.11.

Listing 3.11 Implementing the Dispose Method (ch03_11.cs)

class ch03_11
{
 static void Main()
 {
  Worker worker = new Worker();
  worker.Dispose();
 }
}

public class Worker: System.IDisposable
{
 private bool alreadyDisposed = false;

 public Worker()
 {
  System.Console.WriteLine("In the constructor.");
 }

 public void Dispose(bool explicitCall)
 {
  if(!this.alreadyDisposed)
  {
   if(explicitCall)
   {
   System.Console.WriteLine("Not in the destructor, " +
    "so cleaning up other objects.");
   // Not in the destructor, so we can reference other objects.
   //OtherObject1.Dispose();
   //OtherObject2.Dispose();
   }
   // Perform standard cleanup here...
   System.Console.WriteLine("Cleaning up.");
  }
  alreadyDisposed = true;   
 }

 public void Dispose()
 {
  Dispose(true);
  System.GC.SuppressFinalize(this);
 }

 ~Worker()  
 {
  System.Console.WriteLine("In the destructor now.");
  Dispose(false);
 }
}

Here's what you see when you run ch03_11.cs. Note that the object was only disposed of once, when we called Dispose ourselves, and not by the destructor, because the object had already been disposed of:

C:\>ch03_11
In the constructor.
Not in the destructor, so cleaning up other objects.
Cleaning up.

Renaming Dispose

Sometimes, calling the Dispose method Dispose isn't appropriate. On some occasions, for example, Close or Deallocate might be a better name. C# still recommends you stick with the standard Dispose name, however, so if you do write a Close or Deallocate method, you can have it call Dispose.

Here's another thing to know if you're going to use Dispose—you don't have to call this method explicitly if you don't want to. You can let C# call it for you if you add the using keyword (this is not the same as the using directive, which imports a namespace). After control leaves the code in the curly braces following the using keyword, Dispose will be called automatically. Here's how this keyword works:

using (expression | type identifier = initializer){}

Here are the parts of this statement:

  • expression—An expression you want to call Dispose on when control leaves the using statement.

  • type—The type of identifier.

  • identifier—The name, or identifier, of the type type.

  • initializer—An expression that creates an object.

Here's an example, where Dispose will be called on the Worker object when control leaves the using statement:

class usingExample
{
 public static void Main()
 {
  using (Worker worker = new Worker())
  {
   // Use worker object in code here.
  } 
  // C# will call Dispose on worker here.
 {
}

Forcing a Garbage Collection

Here's one last thing to know about C# garbage collection—although the C# documentation (and many C# books) says you can't know when garbage collection will take place, that's not actually true. In fact, you can force garbage collection to occur simply by calling the System.GC.Collect method.

This method is safe to call, but if you do, you should know that execution speed of your code might be somewhat compromised.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020