#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);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #317 – Constants Can Be Class Members

  1. Pingback: #318 – You Can’t Use the static Modifier On a Constant « 2,000 Things You Should Know About C#

  2. Pingback: #789 – Grouping Constants into Their Own Class | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: