Search code examples
c#parsingtype-conversionapp-configstatic-classes

How to deal with wrong appSettings in a static class?


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 :

  • true or false if application.config's entry is TRUE or FALSE (case insensitive is preferred).
  • false if application.config's entry is anything else.
  • false if application.config does not contain the expected entry.

Solution

  • Well, to achieve the precise goal of what you're asking, you could use:

    public static bool ShouldLog => ConfigurationManager.AppSettings["ShouldLog"]
        ?.Equals("true", StringComparison.OrdinalIgnoreCase) == true;
    

    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.