Reputation: 455
I'm trying to make a variable in my app to be edited in the App.Config file. However I am getting a error saying: Cannot convert string to int.
Code snippet:
/* This is in the .cs file */
private readonly System.Timers.Timer statusEventTimer = new();
private const int statusEventTime = ConfigurationManager.AppSettings["statusTime"];
statusEventTimer.Interval = statusEventTime;
statusEventTimer.Elapsed += StatusEventTimerElapsed;
statusEventTimer.Start();
And this is in the App.Config file
<configuration>
<appSettings>
<add key="statusTime" value="3000"/>
</appSettings>
</configuration>
I've tried to convert the statusTime using ToInt32 but no luck here. Any guesses on what I can do to make this work?
Upvotes: -1
Views: 1019
Reputation: 82524
There are two problems with this code: The first, as others have mentioned in comments, is that the string in configuration file might not be parsable as an int value at all - nothing is stopping whoever is deploying your software to use "Banana" as the value for statusTime
.
The other problem is that constants in c# must be known at compile time. In fact, the compiler is replacing any occurrence of the constant with its value while compiling the c# program.
therefore, you can't use values from configuration for your constants.
What you can do, however, is change the constant to a static readonly field - which have almost all the advantages of constants but can take its value at run time, meaning it can also be used to hold values that aren't known at compile time.
So, to conclude - instead of
private const int statusEventTime = ConfigurationManager.AppSettings["statusTime"];
use
private static readonly int statusEventTime =
int.Parse(ConfigurationManager.AppSettings["statusTime"]);
That is, if you want an exception thrown if the value of statusTime
in configuration isn't parsable as an int.
If you do want to have a default, hard coded value to use in cases where the value isn't configured properly, use int.TryParse
like this:
private const int defaultStatusEventTime = 3000; // or any other value, for that matter...
private static readonly int statusEventTime =
int.TryParse(ConfigurationManager.AppSettings["statusTime"], out var statusTime)
? statusTime
: defaultStatusEventTime;
Upvotes: 4