Main Site Documentation

Question about scope


#1

i would like the variable xyz to be avaialble at all levels, but this does not appear to be happening, even though it is defined in a public section…what is wrong here? I get the error: the name xyz does not exist not in this context …is there a fix?


    public class Program
    {
        // This will hold the main window.
        static Window window;

        public static void Main()
        {
            GlideTouch.Initialize();
            string xyz = "";
            InitWin();
        }

        static void btn_Releaseit(object sender)
        {
           xyz = "testing";     //error the name xyz does not exist not in this context 
        }

        static void btn_PressIt(object sender)
        {
           xyz = "here it is";     //error the name xyz does not exist not in this context 
        }

         static void InitWin()
        {
           ///code
        }
    }
}


#2

You should define

static string xyz;

just below the declaration of “window”.


#3

When a variable is defined inside method, the body of the method is the scope of that variable. Not only it is not visible out of scope it will also be collected after the method exits.


#4

That did the trick!!..
I had already tried plain: string xyz below “window”…adding the word static fixed everything up…how come?

what is the difference between (when it come to the lower level routines)

static string xyz=“hello”;
string xyz= “hello”;


#5

This is because Main is the static method it only has access to the static variables of the class. Non static members are created when an instance of the class is created.


public static string xyzStatic="hello"; 
public string xyzNonStatic= "hello";

So for the variable below you can do this



Debug.Print( "Static member" + Program.xyzStatic);

Program instanceOfTheProgramClass = new Program();
Debug.Print( "Non static member" + instanceOfTheProgramClass.xyzNonStatic);



#6

Please see : http://msdn.microsoft.com/en-us/library/79b3xss3.aspx
or : http://msdn.microsoft.com/en-us/library/98f28cdx(v=VS.100).aspx

Better reading from the source :wink: