mlw4428
mlw4428

Reputation: 520

Would struct be a good way to store program settings in memory?

I'm writing an application and need to store program settings (Input Directory, Output Directory, etc) while the application is running. I'd like to have the program be able to load and use (based on an option) a production environment and a test environment.

I would set the structs up like so:

Class AppSettings
{
    struct prodAppSettings
    {
        var settingName;
        var settingName2;
        var settingName3;
    }

    struct testAppSettings
    {
        var settingName;
        var settingName2;
        var settingName3;
    }
}

I would then, in my main class, load the appropriate settings based off of what environment option the user wanted.

The class AppSettings would handle the loading of the settings (the application will interface with a web service for settings OR it can use, in times where a network connection is unavailable, a XML file that stored the last known good settings). I'm not overly familiar with structs and I'd like to get familiar with them, so this project might be a good place to do that.

EDIT

Clarified a couple of things.

Upvotes: 2

Views: 374

Answers (3)

RE6
RE6

Reputation: 2724

In such cases the classic way of managing your settings is through the built in Settings class

Upvotes: 0

David
David

Reputation: 218887

You already have a class:

class AppSettings

Why not just use that? You can internally structure things further using nested classes:

class AppSettings
{
    public SettingsGroup SomeGroupOfSettings { get; set; }
    // other settings

    public class SettingsGroup
    {
        // properties which are logically grouped together
    }
}

It even seems reasonable to me that there would be (or at least could be) more logic applied here, making a class more and more appropriate.

Structs tend to be good for small groupings of immutable data. A common struct would be two coordinates to form a point, for example. If either coordinate changes, it's an entirely new point and one might as well make a new instance of the struct for it. Larger and potentially more complex things like this really belong in a class which represents more of an "object" than a "grouping of immutable data points."

Upvotes: 6

Marc Gravell
Marc Gravell

Reputation: 1063058

No, basically. Use a class. The number of times you need to use struct is vanishingly small (unless you're writing for XNA etc) - and this isn't one of them. If you use a struct here you're likely to run into at least two problems:

  • passing around a really big struct on the stack (rather than just a reference)
  • lost updates to inner-copies of the struct

and quite possibly a third (torn values, via multi-threaded code)

Upvotes: 10

Related Questions