The peculiarity of constants is that their value can be set only once.
If we have some variables in the program that should not change the value.
Example number PI
we can declare this number a constant.
A keyword is used to declare a constant const
C#
Create a new console application on C# and write the code:
// my class
class MyMath
{
// Constants
public const double PI = 3.14;
public const double MY1;
// designer
public MyMath()
{
MY1 = 8.4; // Error!!! The constant must be defined before compilation
}
}
class Program
{
static void Main(string[] args)
{
double val = 10 * MyMath.PI; // use a constant
MathLib.PI = 3.8; // Error!!! a constant cannot be set multiple times
}
}