Introduction
A constructor is a special method of a class which is used to intialize the data members of the class. Constructor is a special type of method, which will be executed automatically while creating an object. Destructor is a special type of method, which will be executed automatically while destroying an object. Some of main features of contructor are,
- It is a sub procedure declared with the new keyword.
- It doesn't return any value.
- A class can have multiple constructors
- It doesn't mandatory to declare a constructor, the compiler invokes it automatically
Differences between constructor and destructor
Constructor | Destructor |
---|---|
Constructor is a special type of method, executed automatically while creating an object. | Destructor is a special type of method, executed automatically while destroying an object. |
Constrctor name must be same as class name without any return type. | Destructor name must be same as class name with a ~(tild) prefix and without any return type and access specifier. |
Constructors are overloadable. | Destructors are not overloadable. |
Generally constructors are required while initializing instance variables, to open files or to open database connections. | Generally destructors are used to deallocate the memory or to close the files or to close database connections. |
Example on constructor and destructor along with garbage collector concepts:
class Test { public Test() { MessageBox.Show("From Constructor"); } ~Test() { MessageBox.Show("From Destructor"); } } private void button1_Click(object sender, EventArgs e) { Test t1 = new Test(); Test t2 = new Test(); Test t3 = new Test(); }
Observation:
- Here in the above program constructor executed for 3 times destructor also executed for 3 times.
- Destructor will be executed after the project is closed.
- After destructor is executed then within two seconds garbage collector will be loaded into the memory.
- Garbage collector reclaim|deallocate|free the memory allocated for the current project.
- Garbage collector will be done with the help of a predefined class called as System.GC
Comments/Suggestions are invited. Happy coding......!
Comments Post a Comment