EluciusFTW
EluciusFTW

Reputation: 2615

Best way to make data (that may change during run-time) accessible to the whole application?

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!

Upvotes: 5

Views: 2401

Answers (4)

Tigran
Tigran

Reputation: 62246

Define some simple Configuration (say) class:

public static class Configuration 
{
     /*runtime properties */

    public static void LoadConfiguration(..)
    {
       /*Load from file a configuration into the static properties of the class*/
    }


    public static bool SaveConfiguration(...)
    {
       /*Save static properties of the class into the configuration file*/
    }
}

Do not forget naturally default configuration, in case when config file for some reason missed.

Hope this helps.

Upvotes: 3

Hogan
Hogan

Reputation: 70523

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.

Upvotes: 9

swiftgp
swiftgp

Reputation: 1015

You can have a static class with static properties to get and set

Upvotes: 0

Andy
Andy

Reputation: 8562

Sounds like a perfect use of the Settings project page. You setup defaults, they can be modified and saved between runs of your application.

Upvotes: 0

Related Questions