Examples of constructor and destructor usages in C # _c# tutorial

Source: Internet
Author: User
Tags class definition garbage collection modifiers types of functions

The examples in this article describe constructors and destructors usage in C #. Share to everyone for your reference, specific as follows:

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, then executes the constructor of the derived class B ()
b b2 = new B (1);//Executes constructor a () of base Class A, and then executes the constructor B (int)
B b3 = new B (0,1) of the derived class; Executes the constructor a (int) of base class A, and then executes the constructor B (int,int) of the derived class

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 (are called automatically by the system). 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 ()
{
//Here is the user code snippet for scavenging 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.

Note: the CLR

The CLR (Common language Runtime), like the Java Virtual machine, is also a run-time environment that is responsible for resource management (memory allocation and garbage collection) and guarantees the necessary separation between the application and the underlying operating system.

To improve the reliability of the platform and to achieve the level of stability required for transaction-oriented e-business applications, the CLR is also responsible for some other tasks, such as monitoring the operation of the program. According to. NET, the program that runs under CLR monitoring is a "managed" (managed) code, not an application or component that is not under the CLR, that runs directly on bare metal, or that is "unmanaged" (unmanaged) code.

The CLR will monitor a wide variety of common programming errors that have been the primary source of software failure for many years, including access to array elements across bounds, access to unallocated memory space, memory overruns due to excessive data size, and so on.

Read more about C # Interested readers can view the site topics: "C # Programming Thread Usage Tips summary", "C # Operation Excel Skills Summary", "C # XML file Operation Tips Summary", "C # Common control usage Tutorial", "WinForm Control Usage Summary", "C # tutorial on data structure and algorithms, summary of C # array manipulation techniques, and an introductory course on C # object-oriented programming

I hope this article will help you with C # programming.

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.