const or readonly? They're not the same.

Pick the wrong one and it won't even compile.

const or readonly? They're not the same.

The problem

This won't compile.

const Vector3 SpawnPoint = new Vector3( 0, 0, 100 );

const only works with values known when the code is built, like numbers and strings.

The difference

Built in vs set once.

Both stop a value from changing. They differ in when the value is decided.

const
fixed when you compile
readonly
set once, at runtime

The fix

readonly for anything you build.

const float Gravity = 800f; static readonly Vector3 SpawnPoint = new( 0, 0, 100 );

Numbers and strings can be const. Anything you construct, like a Vector3, needs readonly.

Also

readonly can be set in a constructor.

class Weapon{    readonly float _damage;     public Weapon( float damage )    {        _damage = damage;    }}

Each weapon decides its damage once. Nothing can change it after.

The rule

Build time: const. Runtime: readonly.

Numbers, strings
const
Vectors, objects
static readonly
Per object
readonly