views:

196

answers:

4

What is the best way for classes to retrieve/store constants without getting them through web.config?

+4  A: 

You include a static class with all your constants in it.

public static class MyConstants
{
    public const string MyString = "ConstString";
    public const int TestInt = 100;
    // etc...
}
Kelsey
Shouldn't i capitalize all the letters in the member variable?
burnt1ce
I find LOOK_AT_ME_IM_A_CONSTANT_OOOH to be particularly annoying. Maybe you could write it as constantNameOfConstant or something similar.
Matthew Jones
Cool thanks. I agree.
burnt1ce
+1  A: 

XML files and use Application Cache to improve performance or uou can use ASP.NET Configuration Files.

Cleiton
Wouldn't using an XML file be equivalent to using the web.config which is an XML file?
Kelsey
Kelsey: I think it would actually be worse, since you have to parse the Xml yourself. With .config files you can avoid that using the section system provided by .Net.
Mathieu Garstecki
sure. but depending on the data structure that you want to store, it worth.
Cleiton
@Mathieu Garstecki, I edited my post before you say that LOL
Cleiton
+4  A: 

Store them as static in a class, something like this:

public static class DbConstants
{
    public static const string CustomersTableName = "CUST";
    public static const string ProductsTableName = "PROD";
    ...
}

Consider separating them in several classes to group them logically, e.g. one class for DB constants, one class for exception messages, etc.

Mathieu Garstecki
Shouldn't i capitalize all the letters in the member variable?
burnt1ce
The common naming conventions of C# advise against it:http://msdn.microsoft.com/en-us/library/x2dbyw72(VS.71).aspxThis case is covered in the "Read-only Static field" line.
Mathieu Garstecki
+1  A: 

That depends on how "constant" they are. If they are really constant, that is something that would never ever change, then a static class with constants in it. E.g. the number PI, or perhaps a constant containg the name of a field in a table.

If they are more server specific, like connection strings, and you don't want to use the web.config, you might want to check out the option of including a new config file from web.config

<appSettings file="local.config">...</appSettings>

The local.config should then just contain an appSettings element. If the local.config file doesn't exist, it will be ignored. So no exceptions. Any setting that exists in both local.config and web.config, the local.config will be used. You can then share a web config file between many installations, and have local settings overridden in the local.config.

If the constants are more something that a superuser should be able to modify at runtime, then a table in a database is what I would choose. E.g. a if you would let a superuser modify a max password retry attempt count or something.

Pete