Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sample use of a C# Destructor

I'm reading about destructors in C# but I'm having trouble finding a decent use-case for it.

Could someone provide an example of usage with an explanation?

Much, much appreciated.

Update
The code sample in the book implements both a Desctuctor and a Dispose() method, see this code snippet from the book.

class MyClass
{
    bool disposed = false; // Disposal status
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    ~MyClass()
    {
        Dispose(false);
    }
    protected virtual void Dispose(bool disposing)
    {
        if (disposed == false)
        {
            if (disposing == true)
            {
                // Dispose the managed resources. Factored Dispose

            }
            // Dispose the unmanaged resources.

        }
        disposed = true;
    }
}

Marko

like image 281
Marko Avatar asked Dec 17 '22 19:12

Marko


2 Answers

Finalizers are very rarely needed now. They used to be required when you had direct access to native resources - but now you should usually be using SafeHandle instead.

Joe Duffy has an excellent post about this which goes into rather more details than I would be able to write myself - so go read it :)

A quick note on terminology: the ECMA version of the C# spec refers to them as finalizers; the Microsoft version of the spec has always referred to them as destructors and continues to do so.

like image 189
Jon Skeet Avatar answered Jan 05 '23 03:01

Jon Skeet


They're finalizers, not destructors. They're often used to clean up unmanaged resources - if you wrote your own file class, then you would need to use the finalizer to clean up the native file handle.

like image 23
Puppy Avatar answered Jan 05 '23 03:01

Puppy