I'm working with a static class, which should decide whether or not to log information.
It started with:
public static bool ShouldLog { get; set; } = true;
I decided to use an application setting for this:
public static bool ShouldLog { get; set; } =
ConfigurationManager.AppSettings["ShouldLog"];
This does not work, because ConfigurationManager.AppSettings[] returns a string, so this needs to be parsed:
public static bool ShouldLog { get; set; } =
Boolean.Parse(ConfigurationManager.AppSettings["ShouldLog"]);
This is also not good, because, when nothing is filled in in the application.config file, this will generated a NullReferenceException, hence the next attempt:
public static bool ShouldLog { get; set; } =
ConfigurationManager.AppSettings["ShouldLog"] == null ? false :
Boolean.Parse(ConfigurationManager.AppSettings["ShouldLog"]);
This is also not good, because when somebody has entered nonsense into the application.config file, this will generate a TypeInitializationException exception, so the next attempt:
public static bool ShouldLog { get; set; } =
ConfigurationManager.AppSettings["ShouldLog"] == null ? false :
Boolean.TryParse(ConfigurationManager.AppSettings["ShouldLog"]);
This does also not work, because the signature is not result = TryParse() but TryParse(..., out result), so now I'm out of options:
I would like something like:
bool ShouldLog = ...(ConfigurationManager.AppSettings["ShouldLog"]);
Expected result :
trueorfalseifapplication.config's entry isTRUEorFALSE(case insensitive is preferred).falseifapplication.config's entry is anything else.falseifapplication.configdoes not contain the expected entry.
Well, to achieve the precise goal of what you're asking, you could use:
However, I'd personally recommend that instead you use an existing, commonly-used logging framework that provided configuration support, instead of rolling your own. That's likely to provide much more flexibility, as well as avoiding reinventing the wheel.