Best practice for accessing settings from the app config file

I am trying to figure out the best practice for accessing settings from the app config file or the web config. I have seen at least a couple of different approaches to this and I am really not sure which would be better. I am going to outline each of the three methods I have found online, then do some testing and in a later post review my findings.

The first is the very strait forward method of simply using the configurationmanager. You can do something like this:

Another aproach I found was to use a NameValueCollection to hold the values till you need them. If you read the documentation on MSDN about the ConfigurationManager object, it is simply a NameValueCollection under the covers. So you are simply getting the base object and accessing the information directly. You code it something like this:

The last approach seems a little more complicated than the others. Instead of trying to explain I will just post the code. The first thing to do is create a class object to access our appsettings as follows.

You could do this for all your app settings. Then you would simply access the values with the following code:

Each of these approaches seems to have its merits and I am sure in the end it will actually be a matter of personal preference to which one gets used. I really want to see if there is a “best” way to access the app config. Many of the books I have read simply use the first method and it may simply be because it is the easiest to understand and get working. As I am doing more looking around I am finding many different ways to accomplish this same simple thing.

Once I have done more research and testing to see if there is a preferred method I will create another post and show my results. I don’t really think there is a performance difference with any of these three methods, but I think it will be interesting to find out. Also I would be curious to find out if there is a maintainability difference.

Just some of the things that stand out on the surface:

The first and most obvious is in the last method as far a maintainable code. This one requires you to re-compile everything when you add a new value to the app config. In truth if you are adding a new value to the app config you are doing this for a reason and will most likely you are adding code that requires the new value so you will need to re-compile anyway. So that is really a non-issue.

Changing a value in the app config in all three situations should not require a re-compile, these would be simple changes that can be done on the fly and even in production if needed. So that is a non-issue as well.

Again I am leaning toward this actually being a personal preference on how to accomplish such a simple task, but in the interest of following a scientific method of testing lets see where the research leads.

Look for the next post.