C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: When we compile const values, the values are inserted into the parts of the program that use them—there is no lookup overhead.
Part A: The program accesses the _html constant string in 2 ways. We can read a constant in the same way as a static field.
StaticPart B: Here we show that a constant can be placed in the local scope, like a local variable.
Part C: We cannot reassign consts in a program. This would result in a compile-time error.
C# program that uses const
using System;
class Program
{
const string _html = ".html";
static void Main()
{
// Part A: access constant.
Console.WriteLine(_html);
Console.WriteLine(Program._html);
// Part B: local constant.
const string txt = ".txt";
Console.WriteLine(txt);
// Part C: invalid statements.
// ... This causes a compile-time error.
// _html = "";
// ... This causes a compile-time error also.
// txt = "";
}
}
Output
.html
.html
.txt
C# program that causes left-hand side error
class Program
{
static void Main()
{
const int value = 10;
value = 20;
}
}
Output
Error CS0131
The left-hand side of an assignment must be a variable, property or indexer
C# program that causes constant error
class Program
{
static void Main()
{
int size = 5;
const int value = 10 + size;
}
}
Output
Error CS0133
The expression being assigned to 'value' must be constant
Tip: To fix this error, either modify the constant to make it a variable, or remove the assignment.
Quote: Magic numbers are literal numbers, such as 100 or 47524, that appear in the middle of a program without explanation. If you program in a language that supports named constants, use them instead (Code Complete).