Terje Isaksen Developer blog

2009-11-12 (Thursday)

C# App.Config and static classes

Filed under: Developing — Terje Isaksen @ 17:40
Tags: , ,

To make the application configurable, so one can avoid to rewrite and recompile is to use App.Config.

    <add key = "MySetting" value="1223"/>

To access this – add an reference to System.Configuration and then in the code write

string x = System.Configuration.ConfigurationSettings.AppSettings.Get("MySetting")

Now, this is a little long to write, if it is to be used in many places. The solution is to encapsulate it in a static class.

A static class is a class that don´t needs to be instanciated. The values of the properties are set at start, and cannot be changed. Perfect for config-settings.

using System;
using System.Configuration;

namespace Something
 public static class AppResources
 public static string MySetting =  System.Configuration.ConfigurationSettings.AppSettings.Get( "MySetting" );

No need for set or get here.

And it is used like this:

string x = AppResources.MySetting;

And no () after the property name, of course.


Create a free website or blog at WordPress.com.