Search code examples
c#staticstatic-classes

What is the flow of execution once you access a static variable of a class?


I have a structure on the lines of

public static class BuildVersion
{
    public static Version v1// a Version variable
    {
        get
        {
            isVersionV1Updated=true;
            return getVersion("v1");//this is a helper method to get versions
        }
    }
    public static Version v2
    {
        get {
            isVersionV1Updated=false;
            return getVersion("v2");
        }
    }
    public static bool isVersionV1Updated = false;
    public static Version getVersion(string versionString)
    {
        Console.WriteLine(versionString+" updated");
        //do something
        return requiredVersion;
    }
}

Now, what will happen when I set BuildVersion.isVersionUpdated=true?

  1. I mean, what would be the flow, will variables v1 and v2 get populated?
  2. If yes, will the output print "v1 updated" and "v2 updated" appear as output?
  3. Will it make a difference if I make the class 'BuildVersion'as non-static

P.S. Pardon if the question is too naive, I am curios about the flow of where the control flows when you do "BuildVersion.someVariable"


Solution

  • First thing first, with non-static class you get data in the output window, coz probably when you create the class instance, after that you had fetched v1 & v2.
    To answer your question:
    1. No.When you set isVersionUpdated=true, v1 & v2 still remains untouched.
    2. Not at this moment, but if in your code ,when you will try to get v1 or v2, it will.
    3. Normal classes can have static & non static methods/props so,suit yourself(if you feel later on you might need non static prop & methods).