English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# Learning Notes: In-depth Analysis of Constructors and Destructors

Constructor, Destructor

Constructor:

1If no constructor is provided, the system will automatically provide a default constructor, initializing all members to their default values (reference types to null, value types to 0, bool type to false);

2If a constructor with parameters is provided, the system does not provide a default constructor;

3The constructor can be overloaded: multiple versions of the constructor can be provided, which can be distinguished based on the number and type of parameters;

4The private constructor: it is not possible to instantiate the object through this constructor, and it can be instantiated by calling a static function; when it is used only as a container for some static members or properties, a private constructor can be defined to prevent instantiation;

The general constructor is the instance constructor, which executes the constructor as long as an instance is created;

Static constructor:

1It can only be defined once, and can only run once, and is called by the .NET runtime library before calling any members of the class for the first time;

2It cannot take any parameters, has no access modifiers, and can only access the static members of the class, and cannot access the instance members of the class;

3If the class has some static fields or properties that need to be initialized from an external source before the class is used for the first time, then use the static constructor;

4The static constructor and the parameterless instance constructor can be defined at the same time, and there will be no conflict in which constructor is executed when;

In the constructor, you can call other constructors of the same class: this(), or the constructor of the superclass: base(), which can be called in a similar syntax to inheritance to call other constructors;

The readonly field: Similar to constants, its value cannot be modified, but readonly fields are declared with the readonly keyword, can be uninitialized, initialized in the constructor, and its value cannot be changed after that;

Instantiation of anonymous types: var a = new{f}1="1ad", f2="34", f3=5, f4=6};

Constructor: used to construct an instance of the class

;8226; You cannot define a destructor in a struct. Only classes can use destructors.

;8226; A class can have only one destructor.

;8226; You cannot inherit or overload the destructor.

;8226; You cannot call the destructor. They are automatically called. Controlled by the garbage collector, if the garbage collector considers an object eligible for finalization, it calls the destructor (if any) and recycles the memory used to store the object. The destructor is also called when the program exits

;8226; The destructor has no modifiers and no parameters

You can force garbage collection by calling Collect, but you should avoid doing this most of the time because it can cause performance issues

C# does not require much memory management. This is because the .NET Framework garbage collector implicitly manages the memory allocation and release of objects. However, when your application encapsulates unmanaged resources such as windows, files, and network connections, you should use the destructor to release these resources. When an object is eligible for finalization, the garbage collector runs the Finalize method of the object.

If your application uses expensive external resources, we also recommend that you provide a way to explicitly release resources before the garbage collector releases the object. This can be done by implementing the Dispose method from the IDisposable interface, which performs necessary cleanup on the object. This can greatly improve the performance of your application. Even with this explicit control over resources, the destructor is still a safeguard that can be used to clean up resources in case the call to Dispose fails

class Car
{
  -Car() 
  {
    // … …
  }
}

The destructor implicitly calls the Finalize() method recursively on all instances in the inheritance chain

public class Bus
 {
   protected static readonly DateTime globalStartTime;
   protected int RouteNumber { get; set; }
   static Bus() //Static constructor
   {
 globalStartTime = DateTime.Now;
 Console.WriteLine("Static ctor sets global start time to {0}", globalStartTime.ToLongTimeString());
   }
   public Bus(int routeNum)
   {
 RouteNumber = routeNum;
 Console.WriteLine("{0} is created.", RouteNumber)}
   }
   public void Drive()
   {
 TimeSpan elapsedTime = DateTime.Now - globalStartTime;
 Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",
             this.RouteNumber,
             elapsedTime.TotalMilliseconds,
             globalStartTime.ToShortTimeString());
   }
 }
 class TestBus
 {
   static void Main()
   {
 Bus bus = new Bus(71);
 bus.Drive();
 System.Threading.Thread.Sleep(25);
 Bus bus2 = new Bus(72);
 bus2.Drive();
 System.Console.WriteLine("Press any key to exit.");
 System.Console.ReadKey();
   }
 }
 /* Output:
   Static ctor sets global start time to 10:04:08 AM
   71 is created.
   71 is starting its route 21.00 minutes after global start time 10:04 AM.
   72 is created.
   72 is starting its route 46.00 minutes after global start time 10:04 AM.   
*/

This is the full content of the C# learning notes sorted by the editor, analyzing constructors and destructors in depth. I hope it will be helpful to everyone. Please support the呐喊 tutorial~

You May Also Like