...

/

Constants and Read-Only Fields

Constants and Read-Only Fields

Learn to create fields that are read-only.

Constants

A constant is an immutable field with a value assigned during compilation. Constants can’t be reassigned and their value can’t be modified.

Constants are declared using the const keyword:

public const int PI = 3.14;

Only the primitive types, except for the Object class, can be declared as constants. Any other classes, including user-defined types, can’t be modified with the const keyword.

Access modifiers can be used to control access to constants. The static keyword, however, isn’t allowed, because const fields are static members.

The ...