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

All applications always use some constant values.

I don’t like hard-coded these values ​​in my application in every code, as it significantly reduces maintainability.

I have 2 options:

  • Create an inner class called Constants in the target class and add public const values ​​such as

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

or

  • Create a resource file (.resx) and save my constant values ​​and formulas there.

In my application, I used the second approach. One of the problems that I encountered when using the resource file was that I could not use the optional parameter with them.

eg. below does not work:

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

The error was that the Id value was not determined at run time.

Basically, how would you use and recommend managing your constants for each class? why?

My current approach is that if I have constants that should only be used inside one class, I create a class of static constants in the class. If my constants will be used in several classes or projects, I will put them in a resource file, for example. PageUrls.resx.

Thanks,

+4
source share
2 answers

Personally, I would prefer to have constants defined in classes where they logically belong, similar to (say) DateTime.MinValue .

Then, generally speaking, these public constants are a bit of “code smell”, implying some connection, which should probably be better expressed. Obviously, there is no harm in making them private (or internal) when your code allows.

Sometimes there are common constants that belong globally. They often represent a configuration and should be considered as such.

+3
source

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

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

0
source

All Articles