07 / 07

What is the difference between const and readonly (C#) / final (Java)?

Difficulty: 3/10

const, readonly and final

These keywords all relate to values that should not be changed after a particular point, but their semantics differ significantly. In C#, const represents a compile-time constant and is implicitly static; its value must be known at compile time. readonly is normally an instance or static field that can be assigned only at declaration or in a constructor. In Java, final prevents reassignment of a variable after it has been initialized, but for object references it does not make the referenced object immutable. Therefore, final is closer to 'cannot reassign this variable' than to C# const.

javascript
  1. 1

    C# const: compile-time constant; implicitly static.

  2. 2

    C# readonly: field can be assigned at declaration or in a constructor and then cannot be reassigned.

  3. 3

    Java final: variable/reference cannot be reassigned after initialization.

  4. 4

    A final or readonly reference does not automatically make the referenced object immutable.

  5. 5

    Immutable object design requires the object's own state to be protected from mutation.

  6. 6

    Compile-time constants can have binary compatibility implications when consumed across assemblies/modules, so public constants should be designed carefully.

Follow-up Questions

  • Is readonly the same as immutable?
  • Can a readonly field be assigned in a constructor?
  • What does final mean for an object reference in Java?
  • What is the difference between const and static readonly in C#?
  • What are binary compatibility concerns with public constants?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.