"C # Efficient Programming" Reading notes 13-correct initialization of static member variables

Source: Internet
Author: User

Before you create a type instance, you should initialize all static member variables for that instance. C # provides static initializers and static constructors for this purpose.
A static constructor is a special constructor that will be executed before all other methods are executed and before the variable or property is accessed for the first time.
If you simply allocate space for a member, you can use the initializer syntax instead of a static constructor. If you want to initialize static member variables with more complex logic, you can use a static constructor.
单例模式Is the most common scenario for a static constructor, just declare the instance constructor private, and then add the initializer:

public class MySingleton{    private static readonly MySingleton theOneAndOnly = new MySingleton();    private MySingleton(){}    public static MySingleton TheOnly    {        get { return theOneAndOnly; }    }}

If you have more complex initialization logic for the singleton, you can use the static constructor:

public class MySingleton{    private static readonly MySingleton theOneAndOnly;    private MySingleton(){}    static MySingleton()    {        theOneAndOnly = new MySingleton();        //other code...    }    public static MySingleton TheOnly    {        get { return theOneAndOnly; }    }}

Static constructors have the advantage of catching exceptions when compared to static initializers, because the CLR terminates your program when there is an error in the static constructor and static initializer, and the static constructor that catches the exception can keep the program running, but the disadvantage is that the static constructor can only be initialized once, In the event of an error causing a type to not initialize, the CLR will not attempt to initialize again.

"C # Efficient Programming" Reading notes 13-correct initialization of static member variables

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.