What is constant?
In C#, the term "constant" refers to a value that cannot be changed during the program's execution. Constants are used to represent fixed values that remain the same throughout the program's lifecycle. They are helpful for defining settings, mathematical values, and other fixed data that should not be modified.
In C#, you can create constants using the 'const' keyword. Here's the syntax for declaring a constant:
const dataType constantName = value;
Here, 'dataType' is the data type of the constant, 'constantName' is the identifier for the constant, and value is the fixed value assigned to the constant.
Here's an example of using constants in C#:
using System;
class Program
{
const int MyConstant = 42;
static void Main()
{
int x = MyConstant;
Console.WriteLine("The value of x is: " + x);
}
}
In this example, 'MyConstant' is a constant with a value of '42', and it cannot be changed throughout the program's execution. The 'Main()' method uses this constant by assigning its value to the variable 'x' and then prints the value of 'x'.
Values can only be assigned to constants during their declaration; it is not possible to assign values to constants later during execution. Attempting to do so will result in a compilation error as shown below:
Some points to remember about contstants:
-
These values are assigned at compilation time and are often referred to as literals.
- Only built-in data types in C# (excluding System.Object) such as int, decimal, double, char, and string, as well as enumerations, can be declared as constants. User-defined data types like struct, arrays, and classes cannot be used as constants.
- Additionally, methods, properties, and events cannot be declared as constants in C#.
- Constants are immutable values that are known at compile time and cannot be changed during the program's execution.