03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Events ❘ 775<br />

To create a destructor, create a method named after the class with a ~ character in front of it. For<br />

example, the following code shows a destructor for the Person class.<br />

~Person()<br />

{<br />

// Free unmanaged resources here.<br />

...<br />

}<br />

To allow a program to free resources before an object is destroyed, you can give the class a Dispose<br />

method and implement the IDisposable interface.<br />

The following list summarizes the key destruction issues.<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

The destructor is called automatically when an object is destroyed.<br />

The destructor cannot refer to managed objects because they may have already been<br />

destroyed. In particular, the destructor cannot free managed resources because they may<br />

have already been destroyed.<br />

The destructor must free unmanaged resources. This is the last chance the object has for<br />

freeing those resources.<br />

Instead of making the program wait an unknowable amount of time for the destructor to<br />

execute, you can provide a Dispose method that disposes of all resources when the object<br />

is done with them.<br />

If you implement the IDisposable interface, the using statement calls Dispose automatically.<br />

Either it must be safe for the Dispose method and the destructor to both run, or you can<br />

ensure that they both can’t run by making the Dispose method call GC.SuppressFinalize.<br />

Events<br />

An event lets an object notify the application that something potentially interesting has occurred.<br />

Following is the syntax for declaring an event.<br />

«attributes» «accessibility» «new|virtual|override|abstract|sealed» «static»<br />

event delegate name;<br />

The following list describes the declaration’s pieces.<br />

➤➤<br />

➤➤<br />

➤➤<br />

attributes—Attributes provide extra information about the event for use by the compiler,<br />

the runtime system, and other tools.<br />

accessibility—This can be public, private, protected, internal, or protected<br />

internal and is similar to the accessibility for other items such as classes, properties, and<br />

methods.<br />

new|virtual|override|abstract|sealed—These are similar to the keywords used by<br />

methods described in Chapter 6, “Methods.” They have the following meanings:<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!