CHAPTER 24

image

Constants

A variable in C# can be made into a compile-time constant by adding the const keyword before the data type. This modifier means that the variable cannot be changed and it must therefore be assigned a value at the same time as it is declared. Any attempts to assign a new value to the constant will result in a compile-time error.

Local constants

A local constant must always be initialized at the same time as it is declared.

static void Main(){   const int a = 10; // compile-time constant} 

The const modifier creates a compile-time constant, and so the compiler will replace all usage of the constant with its value. The assigned ...

Get C# Quick Syntax Reference 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.