Global variables

  • Thread starter Thread starter Claudio
  • Start date Start date
C

Claudio

I have a project that there is a main form and other forms that a call from
the main one. I would like to create a variable that I could set its value
on the mai form and the others forms see and use this value. It is like a
global variable that can be seen from everywhere.
 
Claudio,

You could create a class with a public static member, or perhaps create
a singleton class, like the one presented below:

public class Globals
{
private int globalValue = 0;
private static globalInstance = null;

private Globals()
{
// Do not allow class instances to
// be created explicitly by the
// consumer
}

// This is the method we will call when we want to
// get a hold of the global vavriables in out application.
public static Globals GetInstance()
{
if( globalInstance == null )
globalInstanc = new Globals();
return globalInstance;
}

public int Value
{
get { return this.globalValue; }
set { this.globalValue = value; }
}
}

Then you will do like this in your application

//Form1.cs
Globals g = Globals.GetInstance();
g.Value = 10;

//Form2.cs
Globals g = Globals.GetInstance();
int someValue = g.Value;

NOTE: You could also call it like Globals.GetInstance().Value which
saves you from storing it in an object before using it.

Hope this helps,

//Andreas
 
Just create a class which will store all your global consts or variables, eg

public class Globals {
public static int glValue = 10;
public Globals() {/* Nothing there */}
}

And you can access it as:

int value = Globals.glValue;
 
Back
Top