I am thinking about a way to create a flexible \"settings class\" in C#. The que
ID: 645841 • Letter: I
Question
I am thinking about a way to create a flexible "settings class" in C#. The question is: How to provide a confortable way to provide default values to the settings. I want the programmer to access the default settings as easy as possible using intellisense. Therefore I encapsulated the default values in a subclass of the actual settings class (instead of defining them directly in the settings class).
public class ServerSettings
{
public ServerSettings(int port = ServerSettings.Default.Port,
string anotherSetting = ServerSettings.Default.AnotherSetting)
{
this.Port = port;
this.AnotherSetting = anotherSetting;
}
public int Port { get; set; }
public string AnotherSetting { get; set; }
public class Default
{
public const int Port = 7000;
public const string AnotherSetting = "abcd";
}
}
The programmer now is able to access the default values like this:
ServerSettings.Default.Port
And after typing ServerSettings.Default a list with all available default settings will show up. It's like a "multitype enum".
What do you think of this solution? Do you have any alternative ideas? Or some criticism?
Explanation / Answer
It sounds like you're recreating the Configuration Management class that the .NET framework already provides.
One thing that I've seen done is to provide a wrapper class around the ConfigurationManager so that a default value can be specified in case the requested configuration parameter isn't present or isn't readable in the configuration file.
Using the .NET configuration class buys you a couple of benefits such as caching of the application properties, compatibility with threaded programs, and atomic operations with reading / writing to the configuration file.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.