C# constants
In C#, a constant is a named value that cannot be changed during program execution. Constants are useful for defining values that are known at compile-time and will not change, such as pi (3.14), the number of days in a week (7), or the speed of light (299,792,458 meters per second).
To declare a constant in C#, you use the const
keyword followed by the data type and the name of the constant, and assign a value to it like this:
const int MAXIMUM_AGE = 100; const double PI = 3.14; const string WEBSITE_URL = "https://www.example.com/";
Once a constant is declared and initialized, its value cannot be changed. If you attempt to assign a new value to a constant, a compilation error will occur.
Constants can be used in expressions and statements just like variables, but their values cannot be modified. For example:
const double TAX_RATE = 0.10; double subtotal = 100.0; double tax = subtotal * TAX_RATE; // tax is 10.0 TAX_RATE = 0.12; // compile-time error: cannot modify a constant
Note that by convention, constant names are typically written in all capital letters to distinguish them from variables. It's also a good practice to use constants for values that are used multiple times in the code, as it can help make the code more readable and easier to maintain.