C # - Why is execution done on instance variables when a class constant is specified?

In the next segment of code I am referring to FILE_LOCATION

from outside of this class, and after the execution of threads to this class to access this constant, for some reason, instead of going back to where the constant call was made, execution continues for creating an instance of a singleton.

My question has two parts; why is this happening and how can I get around it? I tried to create two partial classes, one solely for the constant and the other for everything else, but execution still proceeded to another partial class to instantiate the single.

public sealed class Foo
{  
    public static readonly string FILE_LOCATION = @"path\to\file";

    // (singleton code modeled after:
    // http://csharpindepth.com/articles/general/singleton.aspx --fourth     version)
    private static readonly Foo foo = new Foo();

    // Rest of class implementation...
 }

      

The property refers to an instance of the form class on a button click:

public partial class MyForm : Form
{
    public void button1_Click(object sender, EventArgs e)
    {
        string s = Foo.FILE_LOCATION;
        // this location is only reached AFTER the singleton is instantiated.
    }
}

      

+3


source to share


1 answer


To answer your questions in order,



  • This is because C # ensures that all static variables are initialized before you can access any single static variable. When you call a static variable, access FILE_LOCATION

    , then all static variable initializers (including foo

    ) are run . After that, the static constructor is launched . Since there is no explicit static constructor, nothing is done here. Then your code runs. The reason for this is that sometimes the value of a static variable can be initialized depending on another static variable, so you need to initialize them all at the same time.
  • To get around this, instead of using it, public static readonly string FILE_LOCATION

    you can declare it as public const string FILE_LOCATION

    . The const value is determined at compile time, not at run time, so a static variable foo

    will not be initialized when accessed FILE_LOCATION

    . This can work if you can determine the value of the file location at compile time; is this what you can do in your application?
+7


source







All Articles