(1) constructor
<1> unless it is static, the compiler will specify a default constructor for each class without a constructor.
<2> classes cannot be instantiated when the constructor is private.
<3> A derived class can explicitly call the base class constructor through base. When no explicit call is made, the compiler automatically calls the default constructor of the base class.
<4> the base class does not have a default constructor. The derived class must call the base explicitly.
<5> constructors can be marked as public, protected, private, internal, and protected internal.
<6> instance constructor and static constructor. When initializing static variables in a static or non-static class, you must define a static constructor.
<7> private constructor
The significance of a private constructor is to prevent being instantiated. When a class does not want to be called as a static class and it is a static member, you can use a static constructor. Example:
public class Counter{ private Counter() { } public static int currentCount; public static int IncrementCount() { return ++currentCount; }}class TestCounter{ static void Main() { Counter.currentCount = 100; Counter.IncrementCount(); Console.WriteLine("New count: {0}", Counter.currentCount); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }}
<8> C # does not provide a copy constructor. You must write the constructor as needed.
<9> static constructor.
The static constructor is called automatically before the first instance is created or any static member is referenced.
(2) destructor
<1> The Destructor cannot be inherited. The style is the same as that of C ++.
class Car{ ~Car() // destructor { // cleanup statements... }}
<2> The Destructor is automatically called through the garbage collection mechanism.
Programmers cannot control when to call destructor because it is determined by the garbage collector. The garbage collector checks whether there are objects that are no longer used by the application. If the Garbage Collector considers an object to conform to the destructor, it calls the Destructor (if any) and recycles the memory used to store the object. The Destructor is also called when the program exits.
<3> implicit conversion of destructor
protected override void Finalize(){ try { // Cleanup statements... } finally { base.Finalize(); }}