• USA : +1 973 910 5725
  • INDIA: +91 905 291 3388
  • info@tekslate.com
  • Login

Constructors in C# .Net

Constructors

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”

Syntax

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.

Syntax

 

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

 

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 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 ()

 

 

“At TekSlate, we are trying to create high quality tutorials and articles, if you think any information is incorrect or want to add anything to the article, please feel free to get in touch with us at info@tekslate.com, we will update the article in 24 hours.”

0 Responses on Constructors in C# .Net"

Leave a Message

Your email address will not be published. Required fields are marked *

Site Disclaimer, Copyright © 2016 - All Rights Reserved.