Reputation: 147
I'm trying to use App.config and Configuration Manager for the first time. I wanted to use some values in App.config as default parameters for some methods, but this results in an error (not a compile time constant):
public void ThisDoesntWork(string parameter = ConfigurationManager.AppSettings["SettingName"])
{
// Error: not a compile time constant.
}
I kind of understand why this is the case, so I found this workaround:
public void ThisWorks(string parameter = "Use App.config")
{
if(parameter == "Use App.config")
{
parameter = ConfigurationManager.AppSettings["SettingName"]
}
// Rest of method.
}
It should be noted that this could also be used to make the return value of a static method (or anything that isn't a compile time constant) a default parameter's value.
This feels a little odd to me and I was wondering if this was a code smell.
Has anyone used this workaround before and run into any issues? What is the best practice in this situation?
How can I use configuration values as a defaults of parameters of my methods without using hacks and creating code smell?
Upvotes: -1
Views: 143
Reputation: 5144
Rather than using hacks via magic string/null - you should simply create two overloads of your method.
First one that is parameter-less and uses value from app.config to call the second one (which has required parameter without default value).
Nice and clean and eliminates confusion/ambiguity.
Upvotes: 0