Use of C # constructors and destructors

Source: Internet
Author: User
Tags class definition constructor types of functions

Constructors and destructors are two types of functions that seem to be simpler in a class, but there are always some unexpected 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.

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.

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;}
}

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.