In C#, when you create constructors you are setting the stage to place your objects somewhere in memory. However, there may be times where you have to remove those objects from memory either to free up the space for other objects or because you want to clean out those objects that no longer apply to your program. C# gives you the ability to delete these objects by using destructors.
As the name suggests, a destructor destroys objects that you specify. C# employs destructors automatically when it discovers that an object is no longer being used by the code. Destructors are also helpful when you have objects that take up absolute addresses in your memory. The end result is that you have cleaner code that runs more efficiently and you do not have to go on a search and destroy mission. The lack of explicit destructors is a bit of bad news, but because C# takes care of it, you have one less thing to worry about. When your program compiles, C# checks to see if any code in your program does not use a particular object any longer. If C# finds such an instance it adds the destructor code with the void return type automatically.
C# destroys objects completely and thoroughly. Destructors are not inherited - that is, when C# determines that your code is no longer using the object in a base class, it will not go to any other inherited classes to see if the objects exist in those inherited classes. Instead, C# goes through every class one by one. If C# finds an inherited class with the same object, then C# places that object higher on its list of objects to destroy.
After C# finishes its check of objects in all classes, it creates a list of objects to destroy with the objects in inherited classes first on its task list. Then C# goes through its list and destroys the orphan objects one by one. This all happens behind the scenes, but when you open your classes after your project compiles, you can see the destructor code.
Here we discuss the destructors in C# by using simple example. You can create destructors in C# like constructors with extra symbol tilt character(~) as shown below.
class DestructorClass
{
public DestructorClass()
{
Console.WriteLine("Constructor is Calling...../n");
}
~DestructorClass()
{
Console.WriteLine("Destructor is Calling...../n");
}
}
When C# compiler finds destructor in your code it automatically calls the Finalize on the object base class. So the above code converts as below code internally by C# compiler.
protected override void Finalize()
{
try
{
// your code...
}
finally
{
base.Finalize();
}
}