4

In all applications, there are always some constant values that are used.

I don't like hardcoding these values in my application in each code as it reduces maintainability significantly.

I have 2 options:

  1. Create an internal Constants class within your target class and add public const values such as

    internal static class Constants { public const string IdAttribute = "id"; }

or

  1. Create a Resource file (.resx) and store my constant values and formulas there.

I have used the second approach in my application here. One issue I had with using a resource file was that I could not use .NET 4.0 Optional Parameter feature with them.

e.g. the below doesn't work:

public void DoSomething(string id = Resources.Constants.Id)
{
// ..
}

The error was that the value of Id is not determined at runtime.

Basically, which way would you use and recommend to manage your constants for each class? why?

My current approach is that if I have constants that should be used inside one class only, I create a static Constants class inside that class. If my constants are to be used in more than one class or project, I'll put them in a resource file e.g. PageUrls.resx.

Thanks,

The Light
  • 26,341
  • 62
  • 176
  • 258

2 Answers2

4

Personally I'd rather have constants defined in the classes where they logically belong, in a similar way to (say) DateTime.MinValue.

Then, in general making these constants public is a bit of a "code smell", implying some coupling that should probably be expressed in a better way. There's obviously no harm in making them private (or internal) when your code allows.

Sometimes there are overall constants that belong globally, however. These are often actually configuration and should be treated as such.

Jeremy McGee
  • 24,842
  • 10
  • 63
  • 95
1

I personally use resources mostly for constants that are presented to the user. The main advantage is the possibility to localize it.

For internal constants I prefer static readonly to const variables. When they are shared by many classes I would put them into a constants class, otherwise in the class where they are needed

Community
  • 1
  • 1
Stephan
  • 4,187
  • 1
  • 21
  • 33
  • const is better use of memory than static readonly as far as I know. – The Light Oct 06 '11 at 09:19
  • @William: `public const` variables may cause maintenance trouble when they are accessed from other assemblies. Have a look at the linked answer. (Maybe the word "internal" was an unfortunate choice of mine - I meant constants not presented to the user) – Stephan Oct 06 '11 at 09:27
  • I understand the issue const create for other assemblies if its value change in the future but Constants are constants and are not supposed to change so that raised problem is not valid as it has been a design issue in the first place. If you have constant use const, if you don't have constant and you just need an initialized value that may change, use static readonly. – The Light Oct 06 '11 at 10:01