I've been trying to mull over a question I am not sure how to solve and it probably has a simple solution however I am trying to work out a simple solution.
The following scenario is as such. Let's say we have the following variables.
string username;
string password;
string domain;
string location;
and I want to run the same function across them
void AssignValueFromConfigFile()
{
username = ConfigurationManager.AppSettings["username"];
if (username == null)
throw new ValueNotFound("username");
password = ConfigurationManager.AppSettings["password"];
}
..... etc for each one
This is obviously really tedious and the wrong way to do this. We can make this work in a dictionary if we had:
var values = new Dictionary<string,string>() { {"username",""},{"password",""},{"domain",""},{"location",""}}
void AssignValueFromConfigFile()
{
foreach(var val in values)
{
val.Value = ConfigurationManager.AppSettings[val.Key];
if (val.Value == null)
throw new ValueNotFound(val.Value);
}
}
But then we lose the ability to call the local variables and have to know what they are in the dictionary. How is this achieved?
ConfigurationManager
dictionary that... takes a string key?? As far as I see, you can completely ditch this code and just access the config. Side note: That class was superseded a decade ago. You should be using the strongly typed application settings.