C# Constants
Some values should never change while a program runs: the number of days in a week, a maximum file size, a tax rate fixed by law. Marking them as constant documents your intent and lets the compiler stop anyone — including future you — from overwriting them.
The const keyword
A const must be given a value when it is declared, and that value must be known at compile time.
using System;
const int DaysInWeek = 7;
const double Pi = 3.14159;
const string AppName = "Planner";
Console.WriteLine(quot;{AppName}: {4 * DaysInWeek} days in four weeks");
Console.WriteLine(quot;Circle area for r=2: {Pi * 2 * 2}");Planner: 28 days in four weeks
Circle area for r=2: 12.56636
Trying to change a constant is a compile-time error:
const int MaxUsers = 100;
MaxUsers = 200; // error CS0131: The left-hand side of an assignment must be a variable, property or indexerConstants can be built from other constants, because the compiler can still calculate the result:
using System;
const int SecondsPerMinute = 60;
const int MinutesPerHour = 60;
const int SecondsPerHour = SecondsPerMinute * MinutesPerHour;
Console.WriteLine(SecondsPerHour);3600
Class-level constants
Constants are very often declared inside a class, so the whole class (and possibly other code) can use them. A const member is implicitly static: you access it through the class name.
using System;
class Limits
{
public const int MaxPasswordLength = 64;
public const int MinPasswordLength = 8;
}
class Program
{
static void Main()
{
Console.WriteLine(quot;Passwords: {Limits.MinPasswordLength}-{Limits.MaxPasswordLength} characters");
}
}Passwords: 8-64 characters
const versus readonly
const only works for values the compiler can compute: numbers, bool, char, string and enums. For values that are known only at run time — or for other types such as arrays and objects — use a readonly field. It can be set in its declaration or in a constructor, and never again.
using System;
class Config
{
public const string Version = "1.0"; // compile-time constant
public readonly string[] Servers; // set once at run time
public Config()
{
Servers = new[] { "alpha", "beta" };
}
}
class Program
{
static void Main()
{
var config = new Config();
Console.WriteLine(Config.Version);
Console.WriteLine(string.Join(", ", config.Servers));
}
}1.0
alpha, beta
const |
readonly |
|
|---|---|---|
| When the value is fixed | Compile time | Run time (declaration or constructor) |
| Allowed types | Numbers, bool, char, string, enums | Any type |
| Static? | Always (implicitly) | Instance by default; can be static readonly |
| Can be a local variable? | Yes | No (fields only) |
Tip: Name constants in PascalCase (
MaxRetries), the standard .NET convention — notMAX_RETRIESas in C or Java.
Test yourself
Which of these is a valid constant declaration?
- const int Max;
- const int Max = 10;
- const var Max = 10;
- const int[] Values = {1, 2};
You need a field that is set from a configuration file in the constructor and never changes afterwards. What should you use?
- const
- readonly
- static
- var