When I was learning C #, these two functions were put together for discussion. When I attended the lecture, I felt that I had a superficial understanding. So I checked some information and made a comprehensive understanding.
Destructor-the Garbage Collector, which is called when an object is cleared.
A destructor cannot have parameters, any modifiers, and cannot be called. It is called automatically, which is a major difference between it and the constructor. Because the purpose of the Destructor is opposite to that of the constructor, the prefix '~ 'To show the difference.
class First{~First(){System.Diagnostics.Trace.WriteLine("First's destructor is called.");}}class Second : First{~Second(){System.Diagnostics.Trace.WriteLine("Second's destructor is called.");}}class Third : Second{~Third(){System.Diagnostics.Trace.WriteLine("Third's destructor is called.");}}class TestDestructors{static void Main(){Third t = new Third();}}
The derivation is used here. class First is the base class, Second is derived from First, and Third is derived from Second. All three classes have destructor. In Main (), an instance of the class with the largest degree of derivation is created.
Constructor-initialization, which is used for initialization when an object is called. Below is a constructor
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace ConsoleApplication8 {class Program {static void Main (string [] args) {// call the default constructor Employee objEmployee =NewEmployee (); Console. writeLine ("qualification =" + objEmployee_qualification); Console. writeLine ("salary =" + objEmployee_salary) ;}} class Employee {private string _ name; private char _ gender; private string _ qualification; private uint _ salary; // default constructorPublicEmployee () {_qualification = "graduate student ";}}}
The constructor itself has no return value and cannot be called directly. It can only be called when an object is created through the new operator, that is, the initialization class mentioned above. Note that: only when the constructor is declared public can it be called. Private cannot be called. Constructor may have functions or functions.