Static constructors (C # Programming Guide)

Source: Internet
Author: User
Tags modifiers

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.

C#
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 are invoked or member is accessed.    static Simpleclass ()    {        baseline = 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.

bus has a static constructor. " In this example, the class  bus  has a static constructor. bus is created (bus1), the static constructor are invoked to Init Ialize the class. " > When you create the first instance of the  bus  (BUS1), the static constructor is called to initialize the class. bus is created, And that it runs before the instance constructor runs. " The output example verifies that even if you create two instances of  bus , the static constructor runs only once and runs before the instance constructor runs.

c# 
 public class Bus {//Static variable used by all Bus instances.     Represents the time the first bus of the starts its route.     protected static readonly DateTime globalstarttime;     Property for the number of each bus.     protected int Routenumber {get; set;}     Static constructor to initialize the static variable.     It is invoked before the first instance constructor is run.         Static Bus () {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.         Public Bus (int routenum) {routenumber = Routenum;     Console.WriteLine ("Bus #{0} is created.", Routenumber);     }//Instance method. public void Drive () {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, Globalstarttim     E.toshorttimestring ()); }} class Testbus {static void Main () {//The creation of this instance activates the static constructor         .         Bus Bus1 = new bus (71);         Create a second bus.         Bus Bus2 = new bus (72);         Send Bus1 on its. Bus1.         Drive ();         Wait for Bus2 to warm up.         System.Threading.Thread.Sleep (25);         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 ();     }}/* Sample output:static constructor Sets global start time to 3:57:08 PM.     Bus #71 is created.     Bus #72 is created.     Starting it route 6.00 minutes after global start time 3:57 PM.      The starting it route 31.00 minutes after global start time 3:57 PM. */

Static constructors (C # Programming Guide)

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.