Static Constructor (C # programming guide)

Source: Internet
Author: User
Tags visual studio 2010
Visual Studio 2010In other versions, this topic has not been rated.

 

A static constructor is used to initialize any static data or perform a specific operation that only needs to be performed once. The static constructor is automatically called before the first instance is created or any static member is referenced.

C #
class SimpleClass{    // Static variable that must be initialized at run time.    static readonly long baseline;    // Static constructor is called at most one time, before any    // instance constructor is invoked or member is accessed.    static SimpleClass()    {        baseline = DateTime.Now.Ticks;    }}

Static constructors have the following features:

  • The static constructor neither has an access modifier nor a parameter.

  • Before creating the first instance or referencing any static member, the class is automatically initialized by calling the static constructor.

  • Static constructor cannot be called directly.

  • In a program, you cannot control when to execute static constructors.

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

  • Static constructor is also useful when creating packaging classes for unmanaged code. In this case, the constructor can call the loadlibrary method.

  • If a static constructor causes an exception, the constructor will not be called again at runtime, And the type remains uninitialized during the lifetime of the application domain where the program runs.

Example

In this example, the class bus has a static constructor. When you create the first bus instance (bus1), the static constructor is called to initialize the class. The output example demonstrates that the static constructor runs only once even if two instances of the bus are created 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 day 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 not do this in your actual bus schedule program!            Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",                                    this.RouteNumber,                                    elapsedTime.TotalMilliseconds,                                    globalStartTime.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 way.            bus1.Drive();            // Wait for bus2 to warm up.            System.Threading.Thread.Sleep(25);            // Send bus2 on its way.            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.        71 is starting its route 6.00 minutes after global start time 3:57 PM.        72 is starting its route 31.00 minutes after global start time 3:57 PM.         */
See

Reference class and structure (C # programming guide) constructor (C # programming guide) destructor (C # programming guide) concepts 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.