22

There is a debate between my team members about the declaration of a Constants class. We are moving the constant variables into a separate class like below.

public class Constants
{
      public const string StateId = "ST";
      public const string CountryId = "CI";
}

A few of my team members suggested that we declare the class as sealed to avoid overriding option, and a few are suggesting that we mark it as static to avoid instance creation of the Constant class.
However, I prefer to have it as Sealed with a static constructor, since it will help us to initialize the read-only variables in future need. Please give us some advice on this.

migrated from codereview.stackexchange.com Feb 26 '14 at 6:31

This question came from our site for peer programmer code reviews.

  • Whichever what you go, one consideration could be to use an interface in the system rather than the constants class itself to avoid dependencies between the objects and a "Global" type class??? – dreza Feb 26 '14 at 6:27
  • So you agree on making the class static and just asking if you should add a static constructor now or later? I don't see any opposing opinions in your question, please clarify. – Doc Brown Feb 26 '14 at 7:15
  • 3
    recommended reading: Why is asking a question on “best practice” a bad thing? – gnat Feb 26 '14 at 7:20
  • 2
    I don't get your question. If a class has no instance members, you can mark it static. This is completely orthogonal to the presence or absence of a static constructor. – CodesInChaos Feb 26 '14 at 12:46
  • 1
    Are your constants actually constants in the mathematical sense, or is this a form of configuration? – CodesInChaos Feb 26 '14 at 12:47
27

It's not totally clear what your question is, but if the values are truly constant, I don't see a problem with the simple option of:

    public static class LocationConstants
    {
        public const string StateId = "ST";
        public const string CountryId = "CI";
    }

Using static in the class declaration signals your intention for the purpose of this class.

Marc Gravell describes some of the potential issues with constants in this Stack Overflow answer. Only you will know if these are a problem in your codebase, but if the values could ever change, use public static readonly instead of const, else any code referring to the constants will need to be rebuilt if the values change.

  • 1
    One of the caveats you can find using const variables is clearly explained here. Since codebases tend to grow and get more complex, it is better to avoid using const, the performance gain is usually not worth the risks of potential trouble in the future, IMHO. I prefer to use public static readonly variables for constants. – joanlofe Mar 7 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.