What is the class used for. Typically if its for providing application settings you would use a Singleton. This guarantees there is only one in memory for each application instance. It would have to be stored in heap memory so then it could be available application wide.
Add a class to the project, and call it MySingleton
Code:
public sealed class MySingleton
{
static mySingleton instance=null;
private void MySingleton()
{
}
public static MySingleton getInstance
{
get
{
if (instance==null)
{
instance = new MySingleton();
}
return instance;
}
}
}
Then from anywhere in your application declare it like this
Code:
MySingleton mySingle = MySingleton.getInstance();
Now disecting the singleton pattern
Code:
public sealed class MySingleton
public means it is accessible inside and outside the assembly and to non subclasses.
sealed means it cannot be inherited from
Code:
static mySingleton instance=null;
static variables are tied to the class and not the instance. Having a static class variable means there is only one variable to hold a reference to the instance of the singleton.
Code:
private MySingleton()
{
}
The constructor is declared as private in a singleton.
Code:
public static Singleton getInstance
{
get
{
if (instance==null)
{
instance = new MySingleton();
}
return instance;
}
}
This is the plumbing work. Instead of calling 'new' on the class to instantiate a new object (and call the constructor) you call the static method getInstance. Its basically a class factory that only ever returns one instance of one type of class. By checking to see that instance==null before creating a new instance it guarantees you only get a single instance.