Constructors

A constructor is a special type of method, will be executed automatically while an object is about to create. De Constructors is a special type of method, will be executed automatically while an object is about to destroy. Constructors name must be the same as a class name without “RETURN TYPE”

Syntax

Public CL_Name () {   }

De Constructor name must be the same as a class name without a field  ( ~) Prefix and without return type and access specifier.

Syntax  

CL_ Name () { } Constructors are over loadable.

De -Constructors are not overloadable. Generally, constructors will be used to initialize the fields, to open connections or Files, etc.. Generally, deconstructors will be used to De Allocate the memory and to close the connections and files, etc. 

 These core tutorials will help you to learn the fundamentals of .NET. For an in-depth understanding and practical experience, explore Online ".NET Training".

Example on Constructors

Open windows form Application Project à Place a button à Code in GD

 

Class Test

{

Public Test ()

//Constructor

{

Message Box. Show (“From Constructor ”);

}

~ Test ()

// De- Constructor

{

Message Box. Show (“From De -Constructor”)

}

}

/Test

Code for Button 1_click

{

Test t1 = new Test ();

Test t2 = new Test ();

Test t3 = new Test ();

}

Execute the project

  Observations

When the above project is executed, then 3 times the constructor and 3 times de-constructor will be executed. After a project is terminated (closed), then within 2 sec Garbage collector will be loaded into the memory. Garbage collector Reclaims (clears), the memory allocated for the current project. The garbage collector can be invoked programmatically also with the help of GC. Collect ()