
Using Constructors and Destructors in C# (C Sharp)Constructors
and destructors are commonly used in most of your code. But there are
certain concepts about them which most of you might not know. This article
will highlight on those concepts and give you an overview about constructors
and destructors using simple examples. Constructors
are mainly used and triggered while instantiating a class. Here is a simple
example to demonstrate constructors: Output of
this code will be: In this example,
you have overloaded constructors in sampleClass and triggered constructors
while instantiating the class. This is just a simple example. There are
much more interesting characteristics about constructors. They are mentioned
below: Even
if no constructors are defined, default constructor will be executed internally Destructors
in C#: You already
know that garbage collector does the cleanup for you. But they deal with
only managed resources. If your object is accessing any unmanaged resource,
then you can release then inside the destructor. A destructor can be defined
in a class as shown below: class sampleClass
{ Certain guidelines
have to be followed when you use destructors in your code: Unlike
constructors, your class can have only one destructor Constructors
and Destructors Order of Execution during Inheritance: An interesting
feature about constructors and destructors is their order of execution
when they are involved in inheritance. Consider the following example
which deals with constructors and destructors in multilevel inheritance: class baseClass
{ Output of
this code will be: Executing
Constructor of baseClass Note that
destructor is executed in the reverse order when compared to the constructor
execution. Even if you release object, it is up to the garbage collector
to decide when to clean it. Only when garbage collector does the cleanup,
the destructors will be executed.
_______________________________________________________________________
FREE
Subscription
Subscribe
to our mailing list and receive new articles Note
: We never rent, trade, or sell my email lists to Visit
.NET Programming Tutorial Homepage ______________________________________________________ |