Static Constructors

Started by
1 comment, last by kelaklub 19 years, 1 month ago
Hello, this is a CSharp related question. I am relatively new to the language and I was wondering if someone could explain the following to me. I have included the source for a simple little program which I was trying out that has to do with static constructors. I understand the following about static constructors... // IF YOUR CLASS DECLARES A STATIC CONSTRUCTOR, YOU WILL BE // GUARANTEED THAT THE STATIC CONSTRUCTOR WILL RUN BEFORE // ANY INSTANCE OF YOUR CLASS IS CREATED. // YOU ARE NOT ABLE TO CONTROL EXACTLY WHEN A STATIC // CONSTRUCTOR WILL RUN, BUT YOU DO KNOW THAT IT WILL BE AFTER // THE START OF YOUR PROGRAM AND BEFORE THE FIRST INSTANCE IS // CREATED. What bothers me is that since we can't control when a static constructor runs, how does the following line display the current time... Console.WriteLine("HOUR: {0}, MINUTE: {1}, SECOND: {2}", cl_getTime.hour, cl_getTime.minute, cl_getTime.second); An object of the class has not been created, but by referencing the member variables the static constructor is being made to run. I thought it could not be controlled.

//
// readonly FIELDS ALLOW US TO MARK static VALUES AS CONSTANT
//
using System;

public class cl_getTime
{
    // static CONSTRUCTOR
    static cl_getTime()
    {
        // GET THE CURRENT DATE/TIME INFORMATION
        DateTime dt = DateTime.Now;
        hour        = dt.Hour;
        minute      = dt.Minute;
        second      = dt.Second;
    }

    //
    // PUBLIC
    //
    public static readonly int hour;
    public static readonly int minute;
    public static readonly int second;
}

public class cl_main
{
    public static int Main()
    {
        // THE CONSTRUCTOR BEING static GETS INVOKED BEFORE AN OBJECT OF THE CLASS IS CREATED.
        // SINCE THE MEMBERS OF THIS CLASS ARE static WE CAN ACCESS THEM WITHOUT CREATING AN
        // OBJECT OF cl_getTime
        Console.WriteLine("HOUR: {0}, MINUTE: {1}, SECOND: {2}", cl_getTime.hour, cl_getTime.minute, cl_getTime.second);

        // SINCE THE static FIELDS ARE readonly IF YOU TRY TO CHANGE THEM AS THE FOLLOWING
        // COMMENTED LINE SHOWS, THE COMPILER WILL COMPLAIN
        //cl_getTime.hour = 12;
        return 0;
    }
}



Advertisement
I don't quite see what the problem is (aside from the horrid naming convention). Referencing a member variable causes the static constructor to be run. It could be run a few lines before you check the readonly fields, or it could be run right before you check the readonly fields - that part isn't guaranteed.
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis
Oh, sorry about the naming convention. Hey, different strokes. But all that makes sense, I guess I had a very broad view about how the word "control" was being implied. Thanks.

This topic is closed to new replies.

Advertisement