A constant is a variable whose value cannot be changed once it is assigned. Constants are useful for values that must remain the same throughout the program.
To declare a constant in C#, use the const
keyword followed by the type and name:
const int DaysInWeek = 7; const double Pi = 3.14159;
using System; class Program { const int MaxScore = 100; static void Main() { Console.WriteLine("The maximum score possible is: " + MaxScore); // MaxScore = 90; // ❌ Error! Cannot change a constant value. } }
- Improve code readability by giving meaningful names to fixed values.
- Avoid accidental changes to values that should remain the same.
- Make maintenance easier by changing the value in one place only.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!