The most easiest way to get AppSettings in .NET is to use the ConfigurationManager
. It goes like:
The AppSettings
property is just a NameValueCollection
- an association of string keys and string values. You pass in the string key whose value you want and you get the string value back.
So, if your App.config
were like:
The debugSetting
will have the string value “true”. But most often, you don’t want just the string. Even in this example, you want a boolean value to see if debug is enabled or not (contrived, yes). So, you end up doing something like:
Same goes for integers, urls, and so many other types. Get back the string, convert it to the type that is needed, and consume it.
Is there a better way to all this, which is also pretty simple? TypeConverters
to the rescue!
We can define an AppSettings
helper like this:
Here we use TypeDescriptor.GetConverter()
method to get a TypeConverter
for the type T
we want to convert to. Then we get the converted value from the converter by calling its ConvertFromInvariantString
, the input to which is of course the value from the appSetting.
This helper can now be used for various types which have converters. Consider a sample App.config
:
With that config, you can easily get the values you need, in the type that you will use them in:
The above example works for bool
, TestEnum
, Color
and Uri
types. Easy!