EDIT
I've changed my use of the setting from
private int _Capacity = ConfigurationManager.AppSettings["FuelTankCapacity"];
to...
private int _Capacity = Convert.ToInt32(ConfigurationManager.AppSettings["FuelTankCapacity"]);
This solved the problem, however it feels like a lazy fix. There has to be a way to specify an integer type for settings, hasn't there?
ORIGINAL QUESTION
Having created a few settings in my winforms application, I'm having some trouble with one of them.
The setting is meant to specify the maximum capacity of a fuel tank, the value being 2000
(2000 liters).
Unfortunately, the setting is being read as a string value instead of an int even though I specified it should be an integer value.
Here's the App.config
code for this setting:
<setting name="FuelTankCapacity" serializeAs="String">
<value>2000</value>
</setting>
Note that changing the SerializeAs
value to int/Int32 doesn't fix the problem.
I guess the problem is that AppSettings
is of type NameValueCollection
which is according to MSDN
a collection of associated String keys and String values that can be accessed either with the key or with the index.
So taking this route you end up inevitably with a string.
Using the Property
namespace you can access via Settings
the variable directly and hence access the type as you have specified it:
int t = Properties.Settings.Default.FuelTankCapacity;
Here are more information about using settings at runtime
You can access the value of settings with application scope on a read-only basis, and you can read and write the values of user-scope settings. Settings are available in C# through the Properties namespace.