C# Constant Variable

In the previous section, you have learned about the variables in C#. In this section, you will learn about the constant variables.

As from its name we can understand that Constant variables are those type of variables whose value can't be changed from first to end. A constant variable can be declared using cont keyword. Following is the syntax to declare a constant variable.

const datatype identifier;

A Constant value can be of number, string, Boolean or it can be a null reference.

Example of constant variables

const float PI = 3.14F;
const string websiteName = "TutorialsLeader";
 
const int x = 0;
const double x = 5.0, y = 3.0, z = 7.0;

Remarks:

  • Constant variables must be initialized at the time of their declaration.
  • Once the value assigned to a constant variable it can't be changed.
  • The compiler takes care of constant variables at compile time, hence a constant variable can not be initialized with a value taken from another variable.
  • Constants are always implicitly static. The static modifier is not allowed in a constant declaration.

Following are the invalid constant variable declarations and initializations :

const float PI;  // Invalid constant declaration. A constant must be initialized while declaration.
PI = 3.14; 
 
 
float p = 3.14F;
const PI = p; //Constant variable can not be initialized with a value taken from another variable

However A constant variable can participate in a constant expression. Example :

const int x = 5;  
const int y = x + 10;  

This was an overview and explanation of Constant variable in C#. Let's learn about the Data Types in C# in the next Section.