The Light
The Light

Reputation: 27021

How would you manage your constants for each c# class?

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,

Upvotes: 4

Views: 1581

Answers (2)

Stephan
Stephan

Reputation: 4247

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

Upvotes: 1

Jeremy McGee
Jeremy McGee

Reputation: 25200

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.

Upvotes: 4

Related Questions