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 same as class name without “RETURN TYPE”
Public CL_Name ()
De Constructor name must be same as class name with out a field ( ~)
Prefix and with out return type and access specifier.
CL_ Name ()
Constructors are over loadable.
De -Constructors are not over loadable.
Generally constructors will be used to initialize the fields, to open connections or Files etc..
Generally de constructors will be used to De Allocate the memory and to close the connections and files etc.
Example on Constructors
Open windows forms Application Project à Place a button à Code in GD
Public Test ()//Constructor
Message Box. Show (“From Constructor ”);
~ Test () // De- Constructor
Message Box. Show (“From De -Constructor”)
Code for Button 1_click
Test t1 = new Test ();
Test t2 = new Test ();
Test t3 = new Test ();
Execute the project
When a above project is executed , then 3 times constructor and 3 times de-constructor will be executed.
After a project is terminated (closed), then with in 2 sec Garbage collector will be loaded in to the memory.
Garbage collector Re claims (clears), the memory allocated for the current project.
Garbage collector can be invoked programmatically also with the help of GC. Collect ()