#317 – Constants Can Be Class Members

You can declare constants within a method or within a class.

If a constant is declared in a class, it’s treated  implicitly as a static member of the class–specifically, a static field.  Because the constant’s value can’t change, and was initialized when the constant was declared, it is effectively static because there is only a single value.

In declaring the constant at the class level, you do not use the static keyword.

    public class Dog
    {
        public const string Demeanor = "friendly";

Inside the class, you use the constant in the same way that you’d use a static field–referencing it by name.

        public void ShowDogInfo()
        {
            Console.WriteLine("Name: {0}", Name);
            Console.WriteLine("Demeanor: {0}", Demeanor);
        }

Outside of the class, you also use the constant like any other static class member, prefixing it with the name of the class.

            Console.WriteLine(Dog.Demeanor);
Advertisement