I want some variables to be global across the the project and accessible in every form. How can I do this?
+15
A:
yes you can by using static class. like this:
static class Global
{
private static string _globalVar = "";
public static string GlobalVar
{
get { return _globalVar; }
set { _globalVar = value; }
}
}
and for using any where you can write:
GlobalClass.GlobalVar = "any string value"
Wael Dalloul
2009-08-18 13:41:19
+1 for exposing the value through a property; this gives the possibility to later add locking mechanisms if needed, without altering how already existing code accesses the value.
Fredrik Mörk
2009-08-18 13:51:21
Correct me if I'm wrong but _globalVar needs to be marked as static too.
rein
2009-08-18 14:27:57
I've started to wrap my app.config up in a static class, that allows strongly typed access to the settings. That way I like to think I have the best of both worlds - configurability and strong typing)
MPritch
2009-08-18 15:40:23
A:
public static MyGlobals
{
public static string Global1 = "Hello";
public static string Global2 = "World";
}
public class Foo
{
private void Method1()
{
string example = MyGlobals.Global1;
//etc
}
}
-1 for buggy code. These few lines of code are rife with bugs. No class specification, the Global variables are not as marked static ... that's four compilation bugs right there.
Paul Sasik
2009-08-18 14:03:24
thanks all you guys, i am only allowed to select one so the first one got it..but thanks to all...
Junaid Saeed
2009-08-18 14:04:43
A:
One way,
Solution Explorer > Your Project > Properties > Settings.Settings. Click on this file and add define your settings from the IDE.
Access them by
Properties.Settings.Default.MySetting = "hello world";
Steve
2009-08-18 14:21:01