Dominique
Dominique

Reputation: 17565

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 :

Upvotes: 2

Views: 296

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503859

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.

Upvotes: 2

Related Questions