Lecture overview -- Keyboard shortcut: 'u'  Previous page: Static Classes and Partial Classes in C# -- Keyboard shortcut: 'p'  Next page: Objects and Classes -- Keyboard shortcut: 'n'  Lecture notes - all slides and notes together  slide -- Keyboard shortcut: 't'  Textbook -- Keyboard shortcut: 'v'  Help page about these notes  Alphabetic index  Course home  Page 18 : 29
Object-oriented Programming in C#
Classes and Objects
Constant and readonly variables

C# supports constants - marked with const - which are computed and bound at compile time, before the program starts its execution. C# also supports variables - marked with readonly - which can only be assigned when the surrounding object is created. Once the object has been created, these variables are constant (read only) as well.

Constants and readonly variables cannot be changed during program execution

  • Constants declared with use of the const keyword

    • Computed at compile-time

    • Must be initialized by an initializer

    • The initializer is evaluated at compile time

    • No memory is allocated to constants

    • Must be of a simple type, a string, or a reference type

  • Readonly variables declared with use of the readonly modifier

    • Computed at object-creation time

    • Must either be initialized by an initializer or in a constructor

    • Cannot be modified in other parts of the program

/user/normark/oop-csharp-1/sources/c-sharp/constants-readonly/const-readonly-simple-legal.csLegal use of constants and readonly variables. This program is explained


/user/normark/oop-csharp-1/sources/c-sharp/constants-readonly/const-readonly-simple-illegal.csIllegal use of constant and readonly variables. This program is explained


Read more about constants in the text book version of this material.