Negative tive C # item13: Use a static constructor to initialize static class members

Source: Internet
Author: User

Before creating any instance of the type, we need to initialize the static member variable of this type. C # can complete this task through the static initialization or static constructor, the static constructor is a special function that is executed before any methods of a class, changes to zero, or attributes are accessed.

We should not use the type example constructor or some non-static methods in the type to initialize static member variables of the type.

If the initialization process of static members is not complex, we can initialize them in the initialization tool of the type. If static members need to perform a lot of logical operations during initialization, then we can extract the initialization process to the static constructor.

We can use a static constructor to implement the singleton mode in the design mode, as shown in the following code.

Code

  1 public class MySingleton
2 {
3 private static readonly MySingleton _theOneAndOnly =
4 new MySingleton( );
5
6 public static MySingleton TheOnly
7 {
8 get
9 {
10 return _theOneAndOnly;
11 }
12 }
13
14 private MySingleton( )
15 {
16 }
17
18 // remainder elided
19  }

Similar to the example initializer, the static initiator runs before the explicit code in the static constructor. Similarly, the static constructor also runs before the static constructor of the base class.

 

Static initializes and constructors provide the clearest Initialization Method for static members of our type. Using this method, the code is both easy to read and error prone. C # uses them to solve the problem of static member initialization in other languages.

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.