Question

Possible Duplicate:
What does the tilde (~) mean in C#?

class ResourceWrapper
{
    int handle = 0;
    public ResourceWrapper()
    {
        handle = GetWindowsResource();
    }
    ~ResourceWrapper()                     //this line here
    {
        FreeWindowsResource(handle);
        handle = 0;
    }
    [DllImport("dll.dll")]
    static extern int GetWindowsResource();
    [DllImport("dll.dll")]
    static extern void FreeWindowsResource(int handle);
}

What does the tilde do on the line indicated.

I thought that it was the bitwise NOT operator, infact I don't really understand that whole block there, (the commented line and the parentheses blovk after it), it isn't a methd, or a parameter or anything, what is it and why is there a tilde before it?

Was it helpful?

Solution

That is destructor. It takes care that all resources are released upon garbage collection.

OTHER TIPS

This implements the finalizer (the Finalize method) of the class. Normally you should not implement a finalizer.

E.g. do this for classes that hold external unmanaged resources but be sure to implement the IDisposable Pattern in this case too.

Like in C++, ~ClassName is the destructor method. It gets called in C# when the object in question gets cleaned up by the garbage collector. Unlike in C++ where there are deterministic times when the destructor is called, there is no way of predicting when it will be called (or even if it will be called) in C#.

What you are probably looking for is the IDisposable pattern, which provides a much better approach to this.

That is a Destructor. It gives you implicit control over releasing resources. That is, it is called by the Garbage Collector. If you want explicit control over the release of resources, you can implement IDisposable Check out Implementing Finalize and Dispose to Clean Up Unmanaged Resources. The Framework Design Guidelines also has more information.

Ack, i just found the answer and can't see how to delete my question. it specifies the destructor of the class

i have no clue about C#, but from what the code does, this looks like a deconstructor, saying

  1. free the resource referenced by handle
  2. set handle to 0 to be sure

would kind of go together with the notion of "not" as well ... :)

i may be wrong though ...

greetz

back2dos

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top