Destructors in C#
Introduction
Before reading this post I will recommend you to read Constructors
in C# post. Dot Net (.NET) framework has an in built mechanism known as Garbage
Collection to deallocate memory occupied by the unused objects. In other word,
destructor is something like method and constructor except that the runtime
calls it after the last reference to object has disappeared. A destructor same
name as the name of the class but it starts with the character ~.
using System;
class ClassRoom
{
private int boycount; //field
public ClassRoom() //default constructor
{
boycount = 30;
}
~ ClassRoom()
{
boycount = 0;
}
static void Main(string[] args)
{
ClassRoom r; //creating a class variable, object
r = new ClassRoom(); //initializing class variable
//or direct use "ClassRoom r =
new ClassRoom();"
int x = r.boycount;
Console.WriteLine(x);
Console.ReadKey();
}
}
There are some restrictions apply to destructors:
(i) Destructors cannot be defined in struct. They are only apply to reference types. We cannot declare a destructor in a value type such as struct. For example:
struct ClassRoom
{
~ClassRoom() {….} //compile-time error will appear
}
(ii) A class can only have one destructor. A single destructor
will flush all unused memory. For example:
class ClassRoom
{
....
~ ClassRoom()
{
//place something
}
~ClassRoom()
{
//place something //compile-time error will appear
}
static void
Main(string[] args)
{
....
}
}
(iii) Destructors cannot be inherited or overloaded.
(iv) Destructors cannot be called. They are invoked
automatically.
(v) A destructor does not take modifiers or have parameters.
(vi) We cannot specify an access modifier such as public for a
destructor. We cannot call destructor in our code as it is part of runtime
calls from garbage collector.
(vii) C# Compiler automatically translates a destructor into an
override of the Object.Finalize method. For example:
class ClassRoom
{
....
~ ClassRoom()
{
//place something
}
....
}
into
class ClassRoom
{
protected override void
Finalize()
{
try
{
//place
something
}
finally
{
base.Finalize();
}
}
}
Why my destructor codes placed in try catch block automatically?
To answer this question think, C# provided us to write our own
destructors code that may be wrong or they may contain some error. So, to
ensure destructor always calls its base class destructor, even if an exception
occurs during your destructor code, only compiler can make this translation, we
do not have freedom to write our own method to override Finalize and even we
cannot call Finalize.
I hope you love this. Please post your feedbacks on this post.
Comments
Post a Comment