X hits on this document

PDF document

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

169 views

0 shares

0 downloads

0 comments

33 / 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 Visual Basic, use the Finalize method in your class like so:

Visual Basic:

Protected Sub Finalize()

End Sub

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 views169
Page views169
Page last viewedMon Dec 05 17:26:59 UTC 2016
Pages73
Paragraphs821
Words15988

Comments