An constant is an identifier used to represent a predefined constant value that does not change during program execution.
Constants are used to avoid repeating literal values in the code and to improve its clarity and readability.
Furthermore, using constants makes updating and maintaining the code easier, as if you need to change a constant’s value, you only need to do it in one place.
If you want to learn more, check out the Introduction to Programming Course
Constant Syntax
The basic syntax for defining a constant in C# is as follows:
public const type name = value;
- type: Specifies the data type of the constant
- name: The unique name given to the constant
- value: The constant value assigned to the constant
For example, let’s see how we can define a constant for the value of PI.
public const double PI = 3.14159;
Console.WriteLine(PI); // Output: 3.14159
PI = 3.5; // ❌ this would give an error, you cannot reassign a constant
Using Constants
Accessing Constants
Constants are accessed using the class name followed by the constant name.
Console.WriteLine(Constants.Pi);
Using in Expressions
Constants can be used in expressions instead of literal values to improve code readability and clarity.
double area = Constants.Pi * radius * radius;
Naming Convention
It is not mandatory, but it is relatively common to use uppercase names for constants to distinguish them from other variables.
public const double PI = 3.14159;
Readonly Variables
Readonly variables (readonly) are similar to constants, but their value can be assigned or changed in the class constructor. Once assigned, their value cannot change. This is useful for defining constants that need to be calculated at runtime or initialized in the constructor.
public class Example
{
public readonly int number;
public Example(int value)
{
number = value;
}
}
In this example, number is a readonly variable that can be assigned in the constructor but cannot be modified afterwards.
Practical Examples
Defining Mathematical Constants
public class MathematicalConstants
{
public const double Pi = 3.14159;
public const double Euler = 2.71828;
}
Defining Configuration Constants
public class Configuration
{
public const int LoginAttemptLimit = 3;
public const string DateFormat = "dd/MM/yyyy";
}
