- Destructors are the special methods that r used to release the instance of the class from memory.
- The main purpose of it is to perform the memory clean up action. the programmer can not have any control to call the destructor.
- The .Net frame work automatically runs the destructor to destroy objects in the memory.
- A single class can have only one destructor.
Declaration of Destructor- Destructor follows the same rules as that of constructors but the difference comes in the functioning.
- Destructor has same name as class name as its class but is prefixed with a '~' called as tilde operator.
- Destructors can not be inherited or overloaded.
example:
using System;
class Addition
{
static int n1,n2;
int total;
}
Addition()
{
n1=5;
n2=3;
total=0;
}
public void operation()
{
total=n1+n2;
Console.WriteLine("The result is {0}", total);
}
~Addition()/*.............. Destructor.............*/
{
Console.WriteLine("Destructor invoked");
}
static void Main(String [] arg)
{
Addition obj=new Addition();
obj.operation();
}
}
note: Even when u dont call the destructor, garbage collector releases the memory.
Garbage Collection- It is a process that automatically frees the memory space which is used for the objects at the time of program execution.
- The memory for the object is freed only after observing the status of the object (i.e when object is no longer in use).
- The decision to invoke the destructor is made by a special program of C# called as garbage collector.
- In C#, you can not destroy an object explicitly in code, in fact it has the feature of garbage collection which destroys the objects for the programmers.
- Garbage collection mainly involves,
- objects get destroyed: doesnt specify when the object is destroyed.
- Only unused objects are destroyed: object is nt deleted unless it holds any reference.
- C# uses two special methods to release the instance of a class from memory
- Finalize()
- Dispose()
- Finalize destructor is a special method that is called from the class to which it belongs or from the derived class.
- It is called only after the last reference of the object is released from the memory.
- .Net frame work automatically runs the Finalize() destructor to destroy objects in the memory. and keep in mind that the Finalize method does nt invoke immediately.
- Dispose() method is called to release a resource, such as a database connection as soon as the object using such a resource is no longer in use.
- Unlike the Finalize() destructor , the Dispose() method is not called automatically, and you must explicitly call it from the client application when an object is no longer needed.
- IDisposable interface contains the Dispose() method. So in order to invoke the Dispose() method a class must implement the IDisposable interface.