O'Reilly logo

C# Primer: A Practical Approach by Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required