Lesson 7 +10 XP

Constants

C# Constants

A constant is a variable whose value cannot change after it's set.

Declaring a constant

Use the const keyword:

const int myNum = 15;
myNum = 20;  // error: cannot change a constant

Why use constants?

  • Prevent accidental changes to important values.
  • Make code self-documenting - const int daysInWeek = 7 reads clearly.
  • Allow the compiler to optimize the code.

Constants must be initialized

A const must be assigned a value at the time of declaration:

const int x = 10;   // OK
const int y;        // error: must initialize

Naming convention

By convention, constants are often named in PascalCase or UPPER_SNAKE_CASE:

const int MaxSpeed = 200;
const double PI = 3.14159;

const vs readonly

  • const - compile-time constant, always static, must be a compile-time value.
  • readonly - runtime value that can only be set in the constructor, per instance.
class Program
{
  static readonly int Days = 365;   // set once, can differ per instance
}

TL;DR

  • const makes a value unchangeable.
  • Constants must be initialized when declared.
  • Convention: PascalCase or UPPER_SNAKE_CASE.
  • readonly is similar but set at runtime in the constructor.