X hits on this document

PDF document

“Beginning Visual C# 2005 Express Edition Video Series” - page 54 / 73





54 / 73

Introducing Destructors

Before the object is destroyed, you can write code to clean up your application, which might include closing any open references to files or databases. This is called a Destructor in Object Oriented terminology, and to create a Destructor in C#, create a method that is named the same as the class preceded by the tilde character (~):


~Car() {


How do you call this method from your application? You don’t. If this method is present, the .NET Runtime will automatically execute the code in this method for you right before the object is being destroyed.

Why use a Destructor? In many classes you will create, you won’t need to. You may choose to use a destructor if:

  • Your class is responsible for opening files. If the class is to be destroyed, then you need to close the files it current has opened. Not doing so may corrupt the file, or prevent other parts of your application from accessing the file at a later time.

  • Your class keeps a connection to a database open as long as an instance of the class is being used. This is not a good idea for many reasons, but I’ve seen it done this way and you could use a destructor for this purpose

  • You want to save the current state of the object to a database or a file for later use within your application.

  • Your class is responsible for working directly with the Windows Application Programming Interface (API) and must carefully “disconnect” from Windows so that the application or Windows (or both) do not become disabled.

Supplemental Readings for the Express Edition Videos Copyright © 2005 LearnVisualStudio.NET


Document info
Document views133
Page views133
Page last viewedThu Oct 27 19:25:40 UTC 2016