Constant Variables

[print-me]

Constant variables, or simply constants, are variables whose value cannot be changed once initialized. Given that fact, constants can only do initialization since forgetting to initialize a constant will produce an error. Constants must be assigned with an initial value, and after that, the value can never be changed at runtime.

To declare a variable as constant, simply use the const keyword. Constant’s name should be in all caps as part of C#’s naming convention. It is not required but it allows you to easily identify which are the constants. Here’s the syntax for defining a constant.

const data_type identifier = initial_value;

Here’s an example of using a constant.

namespace ConstantsDemo
{
    class Program
    {
        public static void Main()
        {
            const int NUMBER = 1; // This is a constant
 
            NUMBER = 10; //ERROR, Cant modify a constant
        }
    }
}

You can see that assigning a value to a constant once it has been declared leads to an error. Another thing to note is that you cannot initialize constants with variables who’s value is not known during compilation. For example, doing the following produces an error.

int someVariable;
const int MY_CONST = someVariable;

You might be wondering why do we need to use constants. Constants allow you to store values that you don’t usually change frequently. Say that your program needs to calculate a value by multiplying it with a certain rate. You can store the rate in a constant and then use that constant in multiple places of your code. Here is an example.

using System;

namespace ConstantsDemo
{
    class Program
    {
        public static void Main()
        {
            const double RATE = 0.5;
 
            Console.WriteLine("The rate is " + RATE);
            double calculated = 100 * RATE;
            
            Console.WriteLine("Calculated = " + calculated);
        }
    }
}

As you can see, the RATE constant variable was used several times. Now if you want to change the rate, then all you have to do is change the value of the constant. All the places of your code that uses that constant will automatically update saving you tedious work of manually updating each place where the rate is used. We are also promoting code reusability which is a good programming practice. You may say that we can do this using a normal variable, but using a constant ensures that we won’t accidentally change the value anywhere in our program. It would be hard to demonstrate this accident in a small program but in larger programs, this mistake is easy to make.