#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.

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

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 comment