what is the best way to have data accessible throughtout the wole application? In my concrete example I load the settings of my application from an XML file into an instance of a Settings-Object, and I don't want to make these some absolute constants because the user should be able to change these (and see the effects) without restarting the program.
Now, I need to use certain of the (properties of the) settings in methods of other classes, but in this way they are not accessible. So in what kind of an 'Object' should I store the settings? I don't think it is good it each method that needs a setting across my application has to look into the XML itself. Also, passing the settings instance into every other class I use seems too cumbersome.
Thanks in advance!
In C# I always use a static classes to provide this functionality. Static classes are covered in detail here, but briefly they contain only static members and are not instantiated -- essentially they are global functions and variables accessed via their class name (and namespace.)
Here is a simple example:
public static class Globals
{
public static string Name { get; set; }
public static int aNumber {get; set; }
public static List<string> onlineMembers = new List<string>();
static Globals()
{
Name = "starting name";
aNumber = 5;
}
}
Note, I'm also using a static initializer which is guaranteed to run at some point before any members or functions are used / called.
Elsewhere in your program you can simply say:
Console.WriteLine(Globals.Name);
Globals.onlineMembers.Add("Hogan");
To re-state in response to comment, static objects are only "created" once. Thus everywhere your application uses the object will be from the same location. They are by definition global. To use this object in multiple places simply reference the object name and the element you want to access.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With