Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigurationManager & Static Class

Tags:

c#

.net

static

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.

like image 416
User Avatar asked Aug 25 '11 11:08

User


1 Answers

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";
like image 153
jani Avatar answered Nov 03 '22 01:11

jani