C # Constructor Summary

Source: Internet
Author: User

constructor function

Constructors are divided into: instance constructors, static constructors, private constructors.

Instance Constructors

1, the name of the constructor is the same as the class name.

2. When you use the new expression to create an object or struct of a class (for example, int), its constructor is called. And usually initializes the data members of the new object.

3. Unless the class is static, a default constructor is automatically generated for classes that do not have constructors, and the object fields are initialized with default values.

4. Constructors can have parameters, and multiple constructors can exist in polymorphic form.

Cases:

classcoords{ Public intx, y; //Instance Constructors (default constructors)     PublicCoOrds () {x=0; Y=0; }    //constructors with two parameters     PublicCoOrds (intXinty) { This. x =x;  This. y =y; }    //overriding the ToString method     Public Override stringToString () {return(String.Format ("({0},{1})", x, y)); }    Static voidMain (string[] args) {CoOrds P1=NewCoOrds (); CoOrds P2=NewCoOrds (5,3); //display results using the Override tostring methodConsole.WriteLine ("CoOrds #1 at {0}", p1); Console.WriteLine ("CoOrds #2 at {0}", p2);    Console.readkey (); }}/*output:coords #1 at (0,0) CoOrds #2 at (5,3)*/

where Coords () is a constructor, such as a constructor without arguments, is called a "default constructor."

CoOrds (int x, int y) are also constructors, and constructors can have parameters that allow polymorphism.

Static Constructors

A static constructor has the following properties:

    • Static constructors do not use access modifiers or do not have parameters.

    • A static constructor is called automatically to initialize a class before the first instance is created or any static members are referenced.

    • You cannot call a static constructor directly.

    • The user cannot control when the static constructor is executed in the program.

    • A typical use of a static constructor is when a class uses a log file and the constructor is used to write entries to this file.

    • Static constructors are also useful for wrapper classes that create unmanaged code, in which case constructors can invoke LoadLibrary methods.

    • If the static constructor throws an exception, the runtime will not call the function again, and the type will remain uninitialized for the lifetime of the application domain in which the program is running.

Constructors and Static constructors:

classtestclass{ Public Static intx =0; //constructor FunctionTestClass () {x=1; }    //Static Constructors    StaticTestClass () {
//Second step, execute x = 2 x=2; }
//First step, the program entry main executes first. Then the public static int x = 0 is executed and the static constructor is executed. Public Static voidMain (string[] args) {Console.WriteLine ("x:{0}", x); //print, x = 2 TestClass Test=NewTestClass (); //The third step executes the constructor, at which point x = 1 Console.WriteLine ("x:{0}", x); //Print x = 1 Console.read (); }}

Main is the entry of the program, and when you execute main, the public static int x = 0 is executed first

Then execute the static constructor, at which point x = 2

Then execute the contents of the main function, print X, at this point x = 2

Initializes the TestClass, then executes the constructor, at which point x = 1

Print x = 1

So, the actual order of execution when a static function of a class is called:

1. Static variables > Static constructors > Static functions

2. Static variables > Static Constructors > Constructors

C # 50 proven ways to improve C # code in Efficient Programming (2nd edition) It says something like this:
The complete process for the type instance. You need to understand the order of these operations, as well as the default initialization of objects. You must ensure that each member variable is initialized only once during construction. The best way to achieve this is to initialize as early as possible.
The following is the sequence of operations for creating the first instance of a type:
(1) static variable set to 0
(2) Execution of static variable initializers
(3) Execute the static constructor of the base class
(4) Performing static constructors
(5) instance variable set to 0
(6) Execute 衯 variable initializer
(7) Executing the appropriate instance constructors in the base class
(8) Execution instance constructors the second and subsequent instances of the same type are executed from step 5th, because the class's constructor executes only once. In addition, steps 6th and 7th are optimized so that the constructor initializer causes the compiler to remove duplicate instructions.

Exercises:

 Public classa{ Public Static ReadOnly intx; StaticA () {x= B.y +1; }} Public classb{ Public Static inty = a.x +1;  Public Static voidMain (string[] args) {Console.WriteLine ("X:{0},y:{1}. ", a.x, y);    Console.ReadLine (); }}

Here's the answer:

 Public classa{ Public Static ReadOnly intx; StaticA () {//The second step, call b.y, here B.y = 0, because the int type is assigned a default value at the initialization stage, and the default value is 0. Last x = 0 + 1 (return to first step)x = B.y +1; }} Public classb{//The first step, call a.x, then execute the static constructor of Class A, waiting to return (the second step returns the a.x = 1, all y = 1 + 1)     Public Static inty = a.x +1;  Public Static voidMain (string[] args) {        //The third step, a.x = 1,y = 2. Console.WriteLine ("X:{0},y:{1}. ", a.x, y);    Console.ReadLine (); } }
answers to the exercises

Detailed Answer:

1, first, each project has and can only have a static class main function as the entry function. The entry function is executed first.

2, because the main function in class B, first initializes the class B. The class is initialized in the following order: Static variables in the class, and then the static constructors are executed.

3, run at first to execute public static int y = a.x + 1 This, when executed, will initialize y to 0, and then calculate the value of Y.

4. When the value of Y is computed, a static variable x is called. Therefore, a is initialized first.

5, initialize a when the first to execute public static readonly int x, first the x is initialized to 0.

6. Then execute A's static constructor x = B.y + 1 At this point y is initialized to 0.

7, Calculate x = 1. Then go back to public static int y = a.x + 1 to get y = 2.

8. Then execute the contents of the main function. Results x=1,y=2

Private Constructors

A private constructor is a special instance constructor. It is typically used in classes that contain only static members. If a class has one or more private constructors and no public constructors, other classes (other than nested classes) cannot create instances of the class.

 Public classprivateconstructor{PrivatePrivateconstructor () {//privatetest a = new Privatetest ();//the comment opens with an error message: Inaccessible because it is protected by a level limit. Because the private constructor cannot be instantiated outside the class.     }     Public classPrivatetest {inti; Privateprivatetest () {i=3; }        Static voidMain (string[] args) {Privateconstructor T=NewPrivateconstructor ();//nested classes allow instantiation. Privatetest p =NewPrivatetest ();//the inside of the class allows instantiation. Console.WriteLine ("i:{0}", P.I);            //Result: I:3        Console.read (); }    }}

Declaring an empty constructor prevents the default constructor from being automatically generated. Note that if you do not use the access modifier for the constructor, it is still private by default. However, it is common to explicitly use the private modifier to clearly indicate that the class cannot be instantiated.

Example:

The singleton pattern uses the property of the private constructor to ensure that the class is not instantiated. C # Singleton mode

Related articles: http://www.cnblogs.com/michaelxu/archive/2007/03/29/693401.html

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/constructors

C # Constructor Summary

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.