You can use the constructor where every time an object is created, and if we want some code to be executed automatically. The code that we want to execute must be placed in the constructor. The general view of the C # constructor is as follows
modifier constructor_name (parameters) {
Modifiers can be private, public, secure or internal. The constructor name must be the name of the class where it is defined. The constructor may take zero or more arguments. A constructor with zero arguments (this is not an argument) is known as the default constructor. Remember that there is no return type for the constructor.
The following class contains a constructor that takes two arguments.
class Complex { private int x; private int y; public Complex (int i, int j) { x = i; y = j; } public void ShowXY () { Console.WriteLine(x + "i+" + y); } }
The next code segment displays 20 + i25 on the command line.
Complex c1 = new Complex (20,25); c1.ShowXY ();
That is, when we create an object of class Complex, it automatically calls the constructor and initializes its data elements x and y. We can say that the constructor is mainly used to initialize the object. Even inside the constructor, you can make very complex calculations. A statement inside the constructor may also throw exceptions.
Destructors
The .NET framework has a built-in mechanism called Garbage Collection to de-allocate memory occupied by unused objects. The destructor implements the statements that must be executed during the garbage collection process. A destructor is a function with the same name as the class name, but starting with the ~ character.
Example:
class Complex { public Complex() {
Remember that a destructor cannot have any modifiers such as private, public, etc. If we declare a destructor with a modifier, the compiler will show an error. Also, the destructor will be presented in only one form without any arguments. There is no parameterized destructor in C #.
Destructors are called automatically and cannot be called explicitly. An object becomes suitable for garbage collection when it is no longer used by the active part of the program. The execution of the destructor can occur at any time after the instance or object becomes suitable for destruction.