Home > C# > Constants in C#

In C# a constant is more like a variable with a fixed value. It can be accessed anywhere in the program but the program cannot change its value during its execution. A programmer must initialize a constant when it is created. i. e. their value is known at compile time. They can be of any built-in datatype i.e. int, double, string etc.
Note: – User-defined data types cannot be declared as constants.
The basic syntax to create constants in C# is:

const data-type const-name = const-value;

E.g.

//an integer constant
const int x = 50; 
//a double constant
const double pie = 3.14;
//a character constant
const char ch = ‘a’; 

When these statements are written inside a program they will define constants with their respective data types. Hence values for x, pi and ch will remain 50, 3.14 & ‘a’ or ascii value of a respectively throughout the whole program. we cannot change this value during execution of program.
Example program
In this example below, we have defined a constant pi of type double. Its value remains same during execution of the program.

using System;

namespace constants
{
    class Program
    {
        static void Main(string[] args)
        {
            const double pi = 3.14;
            double radius;
            Console.Write("Please Enter Radius : ");
            radius = Convert.ToDouble(Console.ReadLine());

            double area;
            area = radius * radius * pi;
            Console.Write("Area = " + area + "\n");
        }
    }
}

Output
Constant
If we try to change its value, we will get an error at compile time. As shown in below example.

using System;

namespace constants
{
    class Program
    {
        static void Main(string[] args)
        {
            const double pi = 3.14;
            double radius;
            Console.Write("Please Enter Radius : ");
            radius = Convert.ToDouble(Console.ReadLine());

            double area;
            area = radius * radius * pi;
            Console.Write("Area = " + area + "\n");
            
            // trying to change value of constant
            pi = 15.6;
        }
    }
}

Output
Error in Constant

Naming Convention for Constant(s)

Just like variables constants are also case sensitive. i.e. x & X are two different constants and hence cannot be used interchangeably. Have a look at below program, and check how it works.
Example Program

using System;

namespace constants
{
    class Program
    {
        static void Main(string[] args)
        {
            const double x = 6.53;
            const double X = 53.6;
            Console.Write("Small x = " + x + "\n");
            Console.Write("Capital X = " + X + "\n");
        }
    }
}

Output
Constant naming example

Recommended naming Convention for constants in C# is Pascal casing for constants.

Leave a Reply

Your email address will not be published. Required fields are marked *