C# Class – Best Practices to Create Constants Class

cclass

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.

Best Answer

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.

Related Topic