C# Constants

A constant is a value that never changes after you define it. Once set, the value is locked — no code can modify it. Constants make your programs safer and more readable.

Why Use Constants?

Imagine you write the number 3.14159 in 50 different places in your code. One day you want to use more decimal places. You must find and update every single occurrence. With a constant, you update one place and every use updates automatically.

┌────────────────────────────────────────────────────────────┐
│               WITHOUT CONSTANT                             │
├────────────────────────────────────────────────────────────┤
│  area = 3.14 * r * r;    ← line 10                         │
│  circ = 2 * 3.14 * r;    ← line 25                         │
│  vol  = 3.14 * r * r * h;← line 60                         │
│                                                            │
│  To update: change 3 places — easy to miss one!            │
├────────────────────────────────────────────────────────────┤
│               WITH CONSTANT                                │
├────────────────────────────────────────────────────────────┤
│  const double PI = 3.14159;   ← defined once               │
│                                                            │
│  area = PI * r * r;           ← line 10                    │
│  circ = 2 * PI * r;           ← line 25                    │
│  vol  = PI * r * r * h;       ← line 60                    │
│                                                            │
│  To update: change PI in 1 place — all uses update!        │
└────────────────────────────────────────────────────────────┘

Declaring a Constant

Use the const keyword before the data type. You must assign a value at declaration time — you cannot leave it blank and assign later.

// Syntax:
// const dataType NAME = value;

const int MAX_PLAYERS = 10;
const double PI = 3.14159;
const string APP_NAME = "MyApp";
const bool IS_DEBUG = false;

Valid and Invalid Constant Declarations

// VALID
const int SPEED = 100;                // literal value — OK
const double TAX = 0.18;             // decimal literal — OK
const string GREETING = "Hello";     // string literal — OK

// INVALID
const int TOTAL;                     // ❌ no value assigned
const int SIZE = GetSize();          // ❌ cannot use method calls
const double RATE = someVariable;    // ❌ cannot use runtime variable

Constants require values that are known at compile time — values the compiler can see and lock in before the program even runs.

Constants vs Variables

┌──────────────────────────────┬──────────────────────────────┐
│ Variable                     │ Constant                     │
├──────────────────────────────┼──────────────────────────────┤
│ Can change value at any time │ Value never changes          │
├──────────────────────────────┼──────────────────────────────┤
│ Declared with type only      │ Declared with const keyword  │
├──────────────────────────────┼──────────────────────────────┤
│ int age = 25; age = 30;      │ const int MAX = 100;         │
│ ← allowed                    │ MAX = 200; ← compiler error  │
├──────────────────────────────┼──────────────────────────────┤
│ Value set at runtime         │ Value set at compile time    │
└──────────────────────────────┴──────────────────────────────┘

Naming Conventions for Constants

C# developers commonly use PascalCase for constants. Some teams use ALL_CAPS with underscores (from older conventions). Both styles are valid — pick one and stay consistent.

// PascalCase style (modern C# preference):
const double GravityOnEarth = 9.81;
const int MaxRetries = 3;

// ALL_CAPS style (older, still common):
const double GRAVITY_ON_EARTH = 9.81;
const int MAX_RETRIES = 3;

Constants Inside a Class

Constants declared inside a class are automatically static — they belong to the class itself, not to any object. You access them using the class name.

class Circle
{
    const double Pi = 3.14159;

    public double GetArea(double radius)
    {
        return Pi * radius * radius;
    }
}

class Program
{
    static void Main()
    {
        Circle c = new Circle();
        Console.WriteLine(c.GetArea(5));   // 78.53975
    }
}

Accessing Class Constants Directly

class MathConstants
{
    public const double Pi = 3.14159;
    public const double E = 2.71828;
}

// Access using class name — no object needed
Console.WriteLine(MathConstants.Pi);   // 3.14159
Console.WriteLine(MathConstants.E);    // 2.71828

The readonly Keyword

C# also has readonly, which is similar to const but more flexible. A readonly field can be assigned once — either at declaration or inside a constructor — but not changed after that.

class Config
{
    public readonly string ServerName;

    public Config(string name)
    {
        ServerName = name;   // assigned in constructor — allowed
    }
}

const vs readonly Comparison

┌────────────────────────┬──────────────────────────────────────┐
│ const                  │ readonly                             │
├────────────────────────┼──────────────────────────────────────┤
│ Value at compile time  │ Value at compile or runtime          │
├────────────────────────┼──────────────────────────────────────┤
│ Cannot use method calls│ Can use method calls or new()        │
├────────────────────────┼──────────────────────────────────────┤
│ Always static          │ Instance or static (you choose)      │
├────────────────────────┼──────────────────────────────────────┤
│ Copied into IL code    │ Read from memory at runtime          │
├────────────────────────┼──────────────────────────────────────┤
│ Best for: numbers,     │ Best for: objects, config values,    │
│ strings, true/false    │ values from constructor              │
└────────────────────────┴──────────────────────────────────────┘

Real-World Example: Game Settings

class GameSettings
{
    public const int MaxPlayers    = 4;
    public const int StartingLives = 3;
    public const double Gravity    = 9.8;
    public const string Version    = "1.0.0";
}

class Game
{
    static void Main()
    {
        Console.WriteLine("Max Players: " + GameSettings.MaxPlayers);
        Console.WriteLine("Version: "     + GameSettings.Version);
        Console.WriteLine("Gravity: "     + GameSettings.Gravity);
    }
}
// Output:
// Max Players: 4
// Version: 1.0.0
// Gravity: 9.8

Quick Summary

┌──────────────────────────────────────────────────────────┐
│  const    → value known at compile time, never changes   │
│  readonly → value set once (at declaration or ctor)      │
│                                                          │
│  Benefits of constants:                                  │
│  ✅ Prevent accidental changes                           │
│  ✅ One update = all uses updated                        │
│  ✅ Code reads like English (MAX_SPEED vs 120)           │
│  ✅ Compiler catches any attempt to reassign             │
└──────────────────────────────────────────────────────────┘

Constants are a small feature with a big impact on code quality. Use them for any value that should never change — speed limits, tax rates, application names, grid sizes, or mathematical constants. Your future self (and your teammates) will thank you.

Leave a Comment

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