Usage of constructors and destructors in C #

Source: Internet
Author: User
Tags class definition constructor contains functions reference require resource types of functions
Function

Absrtact: Constructors and destructors are two types of functions that seem to be simpler in a class, but there are always some unexpected running errors in the actual application process. This paper will introduce the principle of constructor function and destructor and the application in C #, and some matters needing attention in the process of using.

Keywords: constructors, destructors, garbage collector, unmanaged resources, managed resources
A The principle of constructors and destructors

As a more advanced language than C, C # provides a better mechanism to enhance the security of your programs. The C # compiler has a strict type security check function that can almost find all the grammatical problems in the program, which is really helpful to the programmer. But the program passed the compile check does not mean that the error no longer exists, in the "wrong" family, "grammatical error" status can only be regarded as the tip of the iceberg. High-level bugs are often hidden deep and are not easy to spot.

According to experience, many bugs are difficult to detect because the variables are not properly initialized or eliminated, and initialization and cleanup work can easily be forgotten. Microsoft uses object-oriented concepts to design the C # language to fully consider this problem and solve it well: put the initialization of the object in the constructor, and put the cleanup work in the destructor. When an object is created, the constructor is executed automatically. When the object dies, the destructor is automatically executed. This eliminates the need to worry about the initialization and cleanup of forgotten objects.
Two The application of constructors in C #

The name of the constructor is not random, and must be recognized by the compiler to be executed automatically. Its naming method is both simple and reasonable: let the constructor have the same name as the class. In addition to the name, another special function of the constructor is that there is no return value type, which is different from a function that returns a value type of void. If it has a return value type, then the compiler will be overwhelmed. Before you can access a class's methods, properties, or anything else, the first executed statement is a constructor that contains the corresponding class. Even if you do not write a constructor yourself, there will also be a default constructor provided to you.

Class TestClass
{
Public TestClass (): Base () {}//provided by the CLR
}

Several types of constructors are listed below

1) Default constructor

Class TestClass
{
Public TestClass (): Base () {}
}

As described above, it is provided by the system (CLR).
2) Instance Constructors

An instance constructor is a method member that implements the initialization of an instance in a class. Such as:

Using System;
Class Point
{
public double x, y;
Public Point ()
{
this.x = 0;
This.y = 0;
}

Public point (Double x, double y)
{
this.x = x;
This.y = y;
}
...
}

Class Test
{
static void Main ()
{
Point A = new point ();
Point B = new Point (3, 4); Initializing an object with a constructor
...
}
}

Declares a class point, which provides two constructors. They are overloaded. One is the point constructor with no arguments and a point constructor that has two double arguments. If these constructors are not provided in the class, then the CLR will automatically provide a default constructor. However, once a custom constructor is provided in a class, such as point (), or point (Double x, double y), the default constructor will not be provided, and this should be noted.

3) Static constructor

A static constructor is a method member that implements initialization of a class. It is typically used to initialize static data. A static constructor cannot have parameters, cannot have modifiers and cannot be invoked, and the static constructor of a class is invoked automatically when the class is loaded. Such as:

Using System.Data;
Class Employee
{
private static DataSet DS;
Static Employee ()
{
ds = new DataSet (...);
}
...
}

Declares a class employee with a static constructor. Note Static constructors can initialize only static data members, not non-static data members. However, non-static constructors can either assign values to static data members or initialize non-static data members.

If the class contains only static members, you can create a private constructor: Private TestClass () {...}, but private means it is not possible to access the constructor from outside the class. Therefore, it cannot be invoked, and no object can be instantiated by the class definition.

These are the simple uses of several types of constructors, and the following focuses on how the constructors of base classes and derived classes are used in the hierarchy of the class (that is, in the inheritance structure). The initialization of a derived class object is done jointly by the base class and the derived class: the members of the base class are initialized by the constructor of the base class, and the members of the derived class are initialized by the constructor of the derived class.

When you create an object of a derived class, the system calls the constructor of the base class and the constructor of the derived class, which executes the constructor of the base class first, and then the constructor of the derived class. If the derived class has an object member, the constructor of the base class is executed, the constructor of the member object class is executed, and the constructor of the derived class is finally executed.

As for the constructor that executes the base class, by default, the parameterless constructor of the base class is executed, and if you want to execute the parameter constructor of the base class, you must indicate it in the member initialization table of the derived class constructor. Such as:

Class A
{private int x;
Public A () {x = 0;}
Public A (int i) {x = i;}
};

Class B:a
{private int y;
Public B () {y = 0;}
Public B (int i) {y = i;}
Public B (int i, int j): A (i) {y = j;}
};

b B1 = new B (); Executes the constructor a () of base Class A, and then executes the constructor B () of the derived class.
b b2 = new B (1); Executes the constructor a () of base Class A, and then executes the constructor B (int) of the derived class
b B3 = new B (0,1); Executes the constructor a (int) of base class A, and then executes the derived class's

Constructor B (Int,int)

The execution order of the constructors here must be analyzed clearly. In addition, if the parameterless constructor public A () {x = 0} is not provided in base class A, then the parameter constructor a (i) of base class A must be indicated in all constructor member initialization tables of the derived class, as follows:

Class A
{private int x;
Public A (int i) {x = i;}
};

Class B:a
{private int y;
Public B (): A (i) {y = 0;}
Public B (int i): A (i) {y = i;}
Public B (int i, int j): A (i) {y = j;}
};

three. The application of destructor and garbage collector in C #

A destructor is a method member that implements the destruction of an instance of a class. Destructors cannot have parameters, cannot have any modifiers, and cannot be invoked. Because the purpose of the destructor is the opposite of the constructor, prefix ' ~ ' to differentiate it.

Although C # (or, more specifically, the CLR) provides a new memory management mechanism---automatic memory management mechanism (Automatic memory management), the release of the resource can be done automatically through the "garbage collector", which generally does not require user intervention. However, in some special cases, destructors need to be used, such as the release of unmanaged resources in C #.

The release of a resource is usually done automatically through the garbage collector, but there are still some things to look out for in particular:

1. A reference to a value type and a reference type does not actually require a "garbage collector" to free up memory because it automatically frees up memory when they are out of scope because they are stored in stacks (stack);

2. Only the object instance pointed to by a reference to a reference type is saved in the heap (Heap). And the heap because it is a free storage space, so it does not like the "stack" that has the lifetime ("stack" of the element after the end of the lifetime, representing the release of memory), and note that the "garbage collector" Only works on this area;

However, in some cases, when you need to release unmanaged resources, you must resolve them by writing code. Typically, you use destructors to release unmanaged resources, and you can place snippets of code that the user writes to release unmanaged resources in a destructor. It is to be noted that if you do not use unmanaged resources in a class, you must not define the destructor, because the object performs a destructor, and the garbage collector calls the destructor before releasing the managed resource, and then the second time it really releases the managed resource, Two deletion actions cost more than one time. The following code is used to show how destructors are used:

public class Resourceholder
{
...
~resourceholder ()
{
This is the user code snippet for cleaning Up Unmanaged resources
}

}

   Four. Summary

Constructors and destructors are simpler functions in a class, but their use is by no means simple, so flexible and correct use of constructors and destructors can help you better understand the memory management mechanisms of the CLR and better manage the resources in the system.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.