C# const

Sometimes for whatever reason, we might want to have a variable to be initialized and never be allowed to change its value after initialization.

For example consider the value of the Pi which is (3.14…). We know that the value of the Pi will never change no-matter what kind of operation it’s being used for. So If we have a variable with this value, is there any reason to change the value? Obviously not! So in situation like this, we want to make sure under any circumstances this value won’t change.

This is where the const keyword can help.

The const keyword stands for constant and we use it to declare a variable that we know its value after initialization will not change whatsoever.

To use this keyword, all we need to do is to put the keyword behind the data type of a variable when it’s being initialized.

Example:

using System;

namespace quickExample

{
class Program
{
const String fullName = "John Doe";
const int age = 20;
static void Main(string[] args)
{
Console.WriteLine(fullName);
Console.WriteLine(age);
}
}
}

Output:

John Doe

20

Here both fullName and age variables are declared as const and so after initialization, we’re no-longer allowed to change the content of these two variables. Attempting to do so, result a compile time error.