Skip to main content
A local constant in C# is an immutable value declared within the lexical scope of a method, constructor, or block using the const keyword. Its value must be fully evaluated and assigned at compile-time, and it cannot be modified during runtime execution.

Technical Characteristics

  • Compile-Time Evaluation: The expression assigned to a local constant must be resolvable entirely by the compiler. It cannot depend on runtime evaluations, method invocations, or the state of other non-constant variables.
  • Mandatory Initialization: A local constant must be initialized at the exact point of declaration. It cannot be declared uninitialized and assigned a value later in the execution flow.
  • Type Restrictions: Allowed constant types are strictly limited to simple types (e.g., int, double, char, bool, decimal), string, enum types, and reference types (provided the reference type is assigned a literal value of null).
  • Lexical Scoping and Shadowing: The identifier is bound strictly to the enclosing block { ... } and is inaccessible outside this specific lexical environment. If a local constant shares an identifier with a class-level field, the local constant shadows (hides) the class-level field within that local scope. However, declaring a local constant with the same name as a local variable in an enclosing block is not permitted and will result in a compile-time error (CS0136).
  • Explicit Typing: The var keyword cannot be used in conjunction with const. The data type must be explicitly declared.
  • IL Embedding: Local constants do not occupy stack memory at runtime in the same way standard local variables do. The C# compiler evaluates the constant and embeds its literal value directly into the Intermediate Language (IL) instructions wherever the identifier is referenced.

Syntax Visualization

Tired of Poor C# Skills? Fix That With Deep Grasping!Learn More