tags:

views:

95

answers:

4

I have code like:

var mySetting = ConfigurationManager.AppSettings["mySetting"];

Is there a way to create properties that encapsulate each setting so I don't have to use string keys like "mySetting"? I know you can do that by creating a "custom configuration section", but I don't want to make another section... I want to use the existing <appSettings> section.

+2  A: 

Yes - use the Visual Studio provided "Settings" classes - use "Add New Item" and then pick "Settings".

This gives you a class with strongly-typed properties (string, int etc.) and all.

This will add the entries it needs in app.config in a custom config section - but it's really all provided for you already, so why reinvent the wheel?

Marc

marc_s
This approach will work great for some project types (e.g. WPF Applications, class libraries, etc) but it won't work for all project types. For example, "Settings File" isn't a New Item option for web applications. Good answer though.
Ben Griswold
@Brian: yes, I agree - it's not *the* solution for everything, but when it's available, I'd use it - don't reinvent everything all the time! :.....
marc_s
+1  A: 

Another option would be create a separate interface that you could use to retrieve the application settings

public interface IFooSettings
{
  int MySettings{get;}
}

public class ApplicationSettings : IFooSettings
{
  public string MySettings{get; private set;}
ApplicationSettings()
{
 MySettings = ConfigurationManager.AppSettings["mySetting"];

}
}

The power of this would be if for some reason you wanted to start saving your configuration in the database the only thing you would need to do is derive a class from IFooSettings to use a database

public class SqlApplicationSettings : IFooSettings
{
SqlApplicationSettings()
{
  //Do Something to populate the settings
}
  public string MySettings{get; private set;}
}

Granted this might be a bit of overkill for your application but it would offer a lot of flexability since you would not be tied to the ConfigurationManager or some other source.

Mark
A: 

Check out Configuration Section Designer which will allow you to do this graphically in Visual Studio.

ifwdev
A: 

http://www.codeproject.com/KB/cs/genuilder.aspx will allow you to do this in ASP.NET projects

mcintyre321