Magic Numbers & Constants
Magic Numbers
Hardcoding literal values (numbers or strings) directly in your code is bad considered practice. For example:
bool hasLicense = true;
int age = 20;
if (age >= 16 && hasLicense)
{
Console.WriteLine("🚗 toot toot");
}
While this code runs fine, what does 16 actually represent? A value like this is called a magic number.
Magic Number Pitfalls: Lets say we need to update all the code to support new regions, you have to hunt down and update every occurrence of
16and that usually causes bugs 🐛
Constants
The fix is to use a named constant. Add the const keyword before the variable, and assign its value at the same time (this is mandatory):
const int LegalDrivingAge = 16; // constants in C# are in PascalCase
bool hasLicense = true;
int age = 20;
if (age >= legalDrivingAge && hasLicense)
{
Console.WriteLine("🚗 toot toot");
}
Once declared, a constant's value is locked in, it cannot be reassigned:
const int UpperLimit;
UpperLimit = 100; // ❌ Error! Constants must be assigned at declaration.