#789 – Grouping Constants into Their Own Class

Constants are declared as class members.  They are effectively static, since there is not a different value for each instance of the class, but you declare them without using the static keyword.

You can use a constant in the class in which it is defined, referring to it by name.  You can also use the constant in other classes, prefixing the name of the constant with the class name.

You can define a constant within a class that contains related data and methods.  It’s also a common practice to group a number of constants into their own class, which is used solely to contain a collection of constants.

    public class Constants
    {
        public const double Pi = 3.14159265358979;
        public const double GoldenRatio = 1.61803398874;
        public const string MNReply = "Not so bad";
    }

Now we can use the constants as follows:

            Console.WriteLine("Pi = {0}", Constants.Pi);

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #789 – Grouping Constants into Their Own Class

  1. Pingback: Dew Drop – February 28, 2013 (#1,506) | Alvin Ashcraft's Morning Dew

  2. Vertex says:

    Hi. Which sense does declaring user-defined type null constant have?
    class First
    {

    }

    class Second
    {
    const First f = null; // allowed but for what?
    const First f2 = new First(); // not allowed
    }

Leave a comment