#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 .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers