Constants and Read-Only Fields
Explore how constants and read-only fields enforce immutability in C# classes. Understand when and how to assign values to each, their memory behavior, and usage constraints to write robust object-oriented code.
We'll cover the following...
We'll cover the following...
C# provides two primary mechanisms for creating immutable members: constants and read-only fields. While they appear similar, they differ significantly in when their values are assigned and how they are stored in memory.
Constants
A constant is an immutable field with a value assigned during compilation. Constants are immutable and cannot be reassigned or modified during program execution.
We declare constants using the const keyword:
public const double PI = 3.14;
This declares a public constant of type double named PI which is immutable after compilation.
You ...