Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Constants

In addition to using literals, there are times when you want to put a value in a variable and freeze it. For example, if you declare a variable called PI and you set it to 3.1459, you want it to stay 3.1459. There is no reason to change it. Additionally, you want to prevent people from changing it.

To declare a variable to hold a constant value, you use the const keyword. For example, to declare PI as stated, you use the following:

const float PI = 3.1459;

You can use PI in a program; however, you will never be able to change its value. The const keyword freezes its contents. You can use the const keyword on any variable of any data type.

TIP

To help make it easy to identify constants, you can enter their names in all capital letters. This makes it easy to identify the fact that the variable is a constant.

  • + Share This
  • 🔖 Save To Your Account