In C#, a constant is a variable whose value cannot be changed after it has been set. Constants are used to represent values that are fixed and unchanging throughout a C# program. In this article, we'll explore how to define constants in C#, the different types of constants available, and the differences between them.
To define a constant in C#, you use the
const keyword. Here's an example of how to define a constant with the name
1const double PI = 3.14159;
This defines a constant of type
double with the name
PI and a value of
3.14159. Once a constant has been defined, its value cannot be changed.
C# supports several types of constants, including:
int: used for whole numbers
double: used for floating-point numbers with decimal places
bool: used for boolean values (
string: used for text values
- and many more
Each constant type has different rules for how it can be used and what values it can hold.
Differences Between Constants
The main difference between constants in C# is their type. Different types of constants have different rules for how they can be used and what values they can hold. For example, a constant of type
int can only hold whole numbers, while a constant of type
float can hold floating-point numbers with decimal places.
Another difference between constants is their scope. Constants can be declared at the global level (outside of any function) or at the local level (inside a function). Local constants can only be accessed and used within the function in which they are declared, while global constants can be accessed and used throughout the entire program.
Constant Naming Convention
By convention, constants in C# are typically named using all uppercase letters, with underscores used to separate words. For example, a constant representing the speed of light might be named