Local Constants

Local Constants

Local constants work much like local variables, with one key difference: once initialized, their value cannot be modified.

Just like local variables, constants must be declared inside a code block.

Constants have two core properties:

  1. They must be assigned a value when declared;
  2. No changes to the value are allowed after declaration.

Basic Constant Syntax

const Type ConstantName = InitialValue;

// const: keyword, must be placed directly before the type
// = InitialValue: mandatory and cannot be omitted
Code language: JavaScript (javascript)

Syntax Rules Explained

Compared with regular field or variable declarations, there are two distinctions:

  1. Add the const keyword before the data type;
  2. An initial value is required, and this value must be resolvable at compile time:
    • Typically primitive literals or expressions built from primitive types;
    • Assignment of null is permitted;
    • Object instance references cannot be assigned (object references are determined at runtime and fail compile-time constant requirements).

class Program
{
    static void Main()
    {
        int a = 10; // this is a variable

        const int b = 20; // this is a constant, similar to a variable
                          // the const keyword marks this as a constant

        a = 100; // variables can be reassigned
        a = 200; // you can change it any number of times

        // Error
        b = 300; // constants cannot be modified; compiler will throw an error

        // Constants improve code readability and maintainability

        
        int c; // declaration
        c = 12; // variables support separate declaration and assignment

        // Constants do not allow separated declaration and initialization
        // Error
        const double d; // declaration
        d = 3.14; // this pattern works for variables only
    }
}Code language: C# (cs)

These two errors occur for different reasons. The first tries to overwrite a constant value. The second separates constant declaration from initialization; both steps must happen together.

Can Class Objects Be Used as Constants?

The expression assigned to constant phone has to be a compile-time constant.

new Phone() allocates heap memory and instantiates an object while the program runs; this is a runtime value.

C# forbids assigning runtime object references to const local constants, which triggers compiler error CS0133.

class Program
{
    static void Main()
    {
        const Phone phone = new Phone();
    }
}

class Phone
{

}Code language: C# (cs)

Additional Keyword Notes

const is not a modifier. It forms an essential part of the declaration syntax and must appear directly before the data type.

Keywords such as private, public and protected are the actual modifiers.

Scope Rules & Example

Local constants follow exactly the same scope rules as local variables. When declared inside a method or code block, they go out of scope once that block finishes executing.

void ShowArea()
{
    const double PI = 3.1416; // declare local constant PI
    for (int radius = 1; radius <= 5; radius++) // output circle areas for radii 1 to 5
    {
        double area = radius * radius * PI; // read value from constant PI
        Console.WriteLine($"Radius: {radius}, Area: {area}");
    }
}
Code language: C# (cs)

The constant PI is only accessible within the ShowArea method and gets discarded after the method finishes running.


class Program
{
    static void Main()
    {
        ShowArea();
    }

    static void ShowArea()
    {
        const double PI = 3.1416; 
        for (int radius = 1; radius <= 5; radius++) 
        {
            double area = radius * radius * PI;
            Console.WriteLine($"Radius: {radius}, Area: {area}");
        }
    }

}
Code language: C# (cs)
Scope of constant PI (marked in red). Just like variables, its scope is bounded by the curly braces {} of its parent block, which is the method body here.

Local Constants

Leave a Reply

Your email address will not be published. Required fields are marked *