views:

913

answers:

5

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
+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
Correct me if I'm wrong but _globalVar needs to be marked as static too.
rein
+5  A: 

Or you could put your globals in the app.config

Rigobert Song
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
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
thanks all you guys, i am only allowed to select one so the first one got it..but thanks to all...
Junaid Saeed
+5  A: 

You can use static class or Singleton pattern.

mykhaylo
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