Click here to Skip to main content
15,904,494 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Finalize() is a destructor in C# and it is used by the GC.
Is there anyway we can use it when we want to free the memory space?
Posted

 
Share this answer
 
Comments
Espen Harlinn 17-Jan-11 14:05pm    
5+ Implementing IDisposable and... is a thorough and well written article
A destructor/finalizer cannot be called directly. It is called automatically when no references to the object remain AND the Garbage Collector (GC) runs.

If you want to free resources you should implement the dispose pattern implementing IDisposable (as below) then consumers of your class have two choices:
1. Call Dispose() when they're done
2. Use a using block and it will be called automatically
C#
public class YourClass : IDisposable
{
    private bool isDisposed;

    ~YourClass()
    {
        Dispose(false);
    }

    public bool IsDisposed
    {
        get{ return isDisposed; }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SupressFinalize(this);
    }
    protected virtual void Dispose(bool disposing)
    {
        if(!isDisposed)
        {
            if(disposing)
            {
                // dispose managed resources here
            }
            // dispose unmanaged resources here
            isDisposed = true;
        }
    }
}
 
Share this answer
 
Hi,

Google is always our friend. First Google it Man!. For your question title in google i got 76,200 results. Destructor in C#[^]

One of those results, Click Here[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900