To set a constant in C#, use the const keyword. Once you have initialized the constant, on changing it will lead to an error.
Let’s declare and initialize a constant string −
const string one= "Amit";
Now you cannot modify the string one because it is set as constant.
Let us see an example wherein we have three constant strings. We cannot modify it after declaring −
Example
using System;
class Demo {
const string one= "Amit";
static void Main() {
// displaying first constant string
Console.WriteLine(one);
const string two = "Tom";
const string three = "Steve";
// compile-time error
// one = "David";
Console.WriteLine(two);
Console.WriteLine(three);
}
}Output
Amit Tom Steve
As shown above, if I will try to modify the value of constant string one, then it will show an error −
// compile-time error // one = "David";