C # static Constructors

Source: Internet
Author: User

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. For example:

class nlog{  //  private Constructor:  private  NLog () {}     Publicstaticdouble//2.71828 ...}

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 a private constructor by default. However, it is common to explicitly use the private modifier to clearly indicate that the class cannot be instantiated.
A private constructor can be used to block the creation of an instance of a class when there is no instance field or instance method (such as the Math Class) or when the method is called to obtain an instance of the class. If all the methods in a class are static, consider making the entire class static.

The following is an example of a class that uses a private constructor.

 Public classcounter{PrivateCounter () {} Public Static intCurrentcount;  Public Static intIncrementcount () {return++Currentcount; }} classtestcounter{Static voidMain () {//If You uncomment the following statement, it'll generate//An error because the constructor is inaccessible://Counter acounter = new Counter (); //ErrorCounter.currentcount= -;    Counter.incrementcount (); Console.WriteLine ("New count: {0}", Counter.currentcount); //Keep the console window open in debug mode.Console.WriteLine ("Press any key to exit.");  Console.readkey (); }}

Output:

101

Note that if you uncomment the following statement in the example, it generates an error because the constructor is inaccessible because of its protection level:

// Counter acounter = new Counter ();   // Error

Static constructors
Static constructors are used to initialize any static data, or to perform specific operations that need to be performed only once. The static constructor is called automatically before the first instance is created or any static members are referenced.

class simpleclass{  //  Static variable that must is initialized at run time.  Static ReadOnly Long baseline;    // Static constructor is called at the most one time, before   any // instance constructor is invoked or member is accessed.  Static Simpleclass ()  {    = DateTime.Now.Ticks;  }}

Static constructors have the following characteristics:

    • Static constructors do not have access modifiers or parameters.
    • The static constructor is called automatically to initialize a class before the first instance is created or any static members are referenced.
    • The static constructor cannot be called directly.
    • In a program, users cannot control when static constructors are executed.

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

Static constructors are also useful when creating wrapper classes for unmanaged code, where the constructor can call the LoadLibrary method.
If the static constructor throws an exception, the runtime will not call the constructor again, and the type will remain uninitialized for the lifetime of the application domain in which the program is running.
In this example, class Bus has a static constructor. When you create the first instance of a Bus (BUS1), the static constructor is called to initialize the class. The output example verifies that even if two instances of the Bus are created, the static constructor runs only once and runs before the instance constructor runs.

 Public classbus{//Static variable used by all Bus instances. //Represents the time the first bus of the starts its route.  protected Static ReadOnlyDateTime Globalstarttime; //Property for the number of each bus.  protected intRoutenumber {Get;Set; } //Static constructor to initialize the static variable. //It is invoked before the first instance constructor is run.  StaticBus () {globalstarttime=DateTime.Now; //The following statement produces the first line of output,//And the line occurs only once.Console.WriteLine ("Static Constructor Sets global start time to {0}", globalstarttime.tolongtimestring ()); }   //Instance constructor.   PublicBus (introutenum) {Routenumber=Routenum; Console.WriteLine ("Bus #{0} is created.", Routenumber); }   //Instance method.   Public voidDrive () {TimeSpan elapsedtime= DateTime.Now-Globalstarttime; //For demonstration purposes we treat milliseconds as minutes to simulate//actual bus times. Do don't do this in your actual bus schedule program!Console.WriteLine ("{0} is starting it route {1:n2} minutes after global start time {2}.",                 This.  Routenumber, Elapsedtime.totalmilliseconds, globalstarttime.toshorttimestring ()); }} classtestbus{Static voidMain () {//The creation of this instance activates the static constructor.Bus Bus1 =NewBus ( in); //Create a second bus.Bus Bus2 =NewBus ( the); //Send Bus1 on its.Bus1.     Drive (); //Wait for Bus2 to warm up.System.Threading.Thread.Sleep ( -); //Send Bus2 on its.Bus2.     Drive (); //Keep the console window open in debug mode.System.Console.WriteLine ("Press any key to exit.");  System.Console.ReadKey (); }}

Output:

Static Constructor SetsGlobalStart Time to3: $: ,PM. Bus # in  iscreated. Bus # the  iscreated. in  isStarting its route6.00Minutes afterGlobalStart time3: $PM. the  isStarting its route31.00Minutes afterGlobalStart time3: $Pm.

C # static Constructors

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.