Monday, 18 March 2013

How to call function once only?

C# has no concept of global variables: everything is class scope.
However (just like VB) you can declare a static class and access everything in it as if they were global:
public static class Globals
   {
   public static int MyGlobalValue = 42;
   }
 
...
 

private void MyMethodSomewhereInAClass()
   {
   Console.WriteLine(Globals.MyGlobalValue);
   MyGlobalValue += 23;
   }
Technically, the class does not need to be static, but since you should not need to instatiate it, it is a good idea.


In the class file:

public static class Config
{
   
    public static bool pagerSettings;
    static Config()  //constructor
    {
        pagerSettings = false;//used for pager links
       
    }
    //get & set the pager settings
    public static bool PagerSettings
    {
        get
        {
            return pagerSettings;
        }
        set
        {
            pagerSettings = true;
        }
    }

}

From the code file:
if (Config.pagerSettings == false)
{
    Config.PagerSettings = true;
}


No comments:

Post a Comment