I would like to use ConfigurationManager
to access some string values from a static class. However, I need to handle specifically the absence of a value or the presence of empty values. Right now I was using type initializers, like
private static readonly string someStr = ConfigurationManager.AppSettings["abc"];
to do the job. However, if a string with key "abc" doesn't exist in App.config
the execution will happilly continue with a null
reference in place of someStr
. What is, then, the best way to validate this value on initialization? A static constructor in which I initialize the value and then check for validity? I heard static constructors are to be avoided and replaced by type initializers when possible.
I'm using something like this:
public static readonly string someStr =
ConfigurationManager.AppSettings["abc"] ?? "default value";
Or to handle empty string:
public static readonly string someStr =
!String.IsNullOrEmpty(ConfigurationManager.AppSettings["abc"]) ?
ConfigurationManager.AppSettings["abc"] : "default value";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With