2.10. const and readonly Data Members

The declaration of a const data member must include an initial value. Moreover, that initial value must be a constant expression—that is, an expression that can be fully evaluated at compile time. For example, the code fragment

class Matrix {
      private const int ms_default_row_size = 4,
                        ms_default_col_size = 4;

declares two const int members initialized with a value of 4. An attempt to modify a const member generates a compile-time error.

A const member can always be initialized with another const member, provided there is no circular dependency. For example, the three const declarations below compile without error, setting x to 10, y to 8, and z to 4:

 class Illustrate { // OK: no circular dependency private ...

Get C# Primer: A Practical Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.