const fields
Learn to define compile-time constants with const.
const fields
A const field is an immutable member whose value is set at compile time. Declaration: public const double Pi = 3.14;.
The compiler substitutes the value at every reference; Pi is replaced with 3.14. So const only accepts constant expressions: numbers, strings and other consts. Runtime values (DateTime.Now, new Random()) are not allowed. Const fields are implicitly static; accessed as ClassName.Pi.
Where is const appropriate?
Const suits values that never change during the app's lifetime and are known at compile time. Math constants (Pi, E), configuration constants (MaxRetries, Timeout) and choice codes are examples.
Because the value is embedded into other assemblies, changing a const forces recompiling all consumers. So in public APIs, static readonly may be preferred. Const cannot hold values that vary per instance.
Exercise Configuration constants
Add public const string Version = "1.0"; and public const int MaxRetries = 3; to AppConfig. In Main, print both.
Show example solution
Add `public const string Version = "1.0";` and `public const int MaxRetries = 3;` to AppConfig. In Main write `Console.WriteLine(AppConfig.Version); Console.WriteLine(AppConfig.MaxRetries);`.
Example solution:
using System;
class AppConfig
{
public const string Version = "1.0";
public const int MaxRetries = 3;
}
class Program
{
static void Main()
{
Console.WriteLine(AppConfig.Version);
Console.WriteLine(AppConfig.MaxRetries);
}
}
Test yourself
-
Fill in the blank: const declaration
class AppConfig { public const string Version = ____; }Show answer
class AppConfig { public const string Version = "1.0"; } -
Which is a valid const declaration?
- public const DateTime Build = DateTime.Now;
- public const int MaxRetries = 3;
- public const Random Rng = new Random();
- public const int Count;
Show answer
public const int MaxRetries = 3; — Correct. `public const int MaxRetries = 3;` uses a compile-time constant.
-
Match: const properties
- compile time
- value is set
- implicitly static
- access via ClassName
- DateTime.Now
- invalid value
- 3.14
- valid value