#316 – Declaring and Using Constants

A constant is a variable whose value does not change during the life of the application.

You declare a constant using the const keyword.  You must initialize a constant when it is declared, specifying a literal value of the appropriate type.

You can use a constant in the same way that you’d use a normal variable of the same type.

            const string DogName = "Kirby";
            const int NumBarks = 3;
            const char NameDelimiter = '-';
            const double FoodVolume = 1.2;

            Dog d = new Dog(DogName);
            d.Bark(NumBarks);
            Console.WriteLine("{0}{1}{2}", NameDelimiter, d.Name, NameDelimiter);
            d.FeedFoodInCups(FoodVolume);

The compiler will generate an error at compile-time if you try to change the value of a constant.

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.

One Response to #316 – Declaring and Using Constants

  1. 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: