Constants in C#

Constants in C# are fixed values that should not change while the program runs. They are useful for values such as mathematical constants, limits, fixed messages, configuration-like values, status codes, and repeated values that need a meaningful name. Instead of writing the same number or string again and again, you can define it once as a constant and use its name throughout the program.

C# gives more than one way to represent fixed values. The most common options are const, readonly, and static readonly. These are related, but they are not identical. Understanding the difference is important because each one has different rules for initialization, runtime behavior, and where it should be used.


What Is a Constant in C#?

A constant is a named value that cannot be changed after it is defined. In C#, the const keyword is used to declare compile-time constants.

const double Pi = 3.14159;
const int MaxLoginAttempts = 3;
const string AppName = "Nerds Do Stuff";

After a constant is declared, assigning a new value to it is not allowed. The compiler rejects the code before the program runs.

A constant gives a fixed value a meaningful name and prevents accidental modification.

Syntax of const in C#

const dataType ConstantName = value;

Example:

const int DaysInWeek = 7;

The value must be assigned at the time of declaration. A const field cannot be declared first and assigned later.

Simple Example of Constants in C#

using System;

class Program
{
    static void Main()
    {
        const double Pi = 3.14159;
        double radius = 5;
        double area = Pi * radius * radius;

        Console.WriteLine($"Area = {area}");
    }
}

Here, Pi is fixed and cannot be changed inside the program. This is better than writing 3.14159 directly in multiple places because the name explains the meaning of the value.

Why Constants Are Used

  • They prevent accidental changes to fixed values.
  • They make code easier to read.
  • They reduce repeated magic numbers and magic strings.
  • They make updates easier when a fixed value must be changed in one place.
  • They communicate that a value is part of the program design.

For example, MaxRetryCount is clearer than simply writing 3 throughout the code. The name explains why the number exists.

Compile-Time Constants

A const value in C# is a compile-time constant. This means the value must be known when the code is compiled. You cannot assign the result of a runtime method call to a const field.

const int Size = 10;          // valid
// const DateTime Now = DateTime.Now; // invalid

DateTime.Now is known only when the program runs, so it cannot be stored in a const. For runtime fixed values, use readonly or static readonly.

Allowed Types for const

C# const values are limited to certain built-in types, enum types, and strings. You cannot create a const object of a custom class type.

Allowed for constExamples
Numeric typesint, double, decimal
Characterchar
Booleanbool
Stringstring
EnumNamed enum values

Constants vs Variables

FeatureVariableConstant
Can value change?YesNo
Must initialize immediately?Not alwaysYes
PurposeStore changing dataStore fixed named values
KeywordNo special keyword requiredconst

Use variables for values that can change. Use constants for values that are part of the rules of the program and should remain fixed.

readonly in C#

The readonly keyword creates a field that can be assigned only during declaration or inside a constructor. Unlike const, a readonly value can be decided at runtime.

class UserSession
{
    private readonly DateTime createdAt;

    public UserSession()
    {
        createdAt = DateTime.Now;
    }
}

This works because createdAt is assigned in the constructor. After that, it cannot be reassigned for that object.

static readonly in C#

static readonly is useful for fixed values that belong to the type itself and may be initialized at runtime. It is often preferred for values that are fixed after startup but cannot be represented as compile-time constants.

class AppInfo
{
    public static readonly DateTime StartedAt = DateTime.Now;
}

The value is set when the type is initialized and cannot be reassigned afterward.

const vs readonly vs static readonly

KeywordWhen Value Is SetBest Use
constCompile timeTrue fixed values known at compile time
readonlyDeclaration or constructorObject-level values fixed after construction
static readonlyType initializationShared runtime values fixed after startup

This distinction matters. If the value is calculated at runtime, it cannot be const. If the value should be fixed per object, use readonly. If the value is shared by the class and fixed after initialization, use static readonly.

Constants and Magic Numbers

A magic number is a number written directly in code without explanation.

if (attempts > 3)
{
    Console.WriteLine("Account locked");
}

This works, but the value 3 has no meaning unless the reader already knows the rule. A constant makes the rule clear.

const int MaxLoginAttempts = 3;

if (attempts > MaxLoginAttempts)
{
    Console.WriteLine("Account locked");
}

Naming Constants in C#

C# constants usually use PascalCase, especially when they are fields or public members.

const int DefaultPageSize = 20;
const string DefaultRole = "User";

Clear names are important because constants often represent rules, limits, or repeated values. A name like MaxUploadSizeMb is much better than Limit because it explains both the meaning and unit.

Class-Level Constants

Constants can be declared inside classes. Class-level constants are useful when the value belongs to that class or module.

class PasswordRules
{
    public const int MinimumLength = 8;
    public const int MaximumLength = 64;
}

You can access these constants using the class name.

Console.WriteLine(PasswordRules.MinimumLength);

Versioning Concern with public const

One advanced detail is that public constants can be copied into consuming assemblies at compile time. If you publish a library and later change a public const, another project may need to be recompiled to see the new value. For public library values that may change, static readonly can be safer.

Constant Expressions in C#

A const value can be initialized using a constant expression. That means the compiler must be able to calculate the final value during compilation without running the program.

const int MinutesPerHour = 60;
const int SecondsPerMinute = 60;
const int SecondsPerHour = MinutesPerHour * SecondsPerMinute;

This works because every value in the expression is already known at compile time. If the expression depends on user input, current time, file data, or a method result, it cannot be used as a const initializer.

Enum Values as Constants

Enum values behave like named constants for a fixed set of choices. They are often better than separate integer constants when the values represent a closed group of states.

enum PaymentStatus
{
    Pending,
    Paid,
    Failed,
    Refunded
}

Using an enum makes the allowed values clear and prevents random unrelated numbers from being used as status values.

Constants vs Configuration

Not every repeated value should become a constant in source code. If a value changes between environments, customers, deployments, or runtime settings, it usually belongs in configuration instead of a const. Examples include connection strings, API keys, feature flags, server URLs, and production limits that operations teams may need to adjust.

A good rule is simple: use constants for program rules that are truly fixed in code, and use configuration for values that may need to change without recompiling the application.

Choosing Between const, readonly, and Configuration

  • Use const for compile-time values such as mathematical constants and fixed labels.
  • Use readonly when each object receives a fixed value during construction.
  • Use static readonly when a shared value is calculated once at startup.
  • Use configuration when the value may change outside the codebase.

Practical Example in a Real Project

Imagine a login system that locks an account after repeated failed attempts. The maximum attempt count, lockout message, and validation limits should not be scattered as raw values in many files. Naming them clearly makes the rule visible and easier to maintain.

class LoginRules
{
    public const int MaxFailedAttempts = 3;
    public const int MinimumPasswordLength = 8;
    public const string LockoutMessage = "Account locked after too many failed attempts.";
}

This is much clearer than repeating 3, 8, and the same message string in controllers, services, and validation code. The constants become a small source of truth for that rule.

Common Mistakes with Constants in C#

  • Trying to assign runtime values to const.
  • Using const when readonly is more appropriate.
  • Creating vague constant names.
  • Using public constants in libraries without understanding versioning behavior.
  • Keeping magic numbers instead of named constants.
  • Using constants for values that genuinely need to change during execution.
Can a const value change in C#?

No. A const value is fixed at compile time and cannot be reassigned after declaration.

What is the difference between const and readonly?

const is a compile-time constant. readonly can be assigned at declaration or in a constructor, so it can use runtime values.

When should I use static readonly?

Use static readonly for shared values that are fixed after type initialization but cannot be known at compile time.

Best Practices for Constants in C#

  • Use const only for true compile-time constants.
  • Use readonly for object-specific values fixed after construction.
  • Use static readonly for shared runtime-initialized values.
  • Give constants meaningful names.
  • Replace repeated magic numbers and strings with named constants.
  • Be careful with public constants in libraries.
  • Include units in names when needed, such as TimeoutSeconds or MaxSizeMb.

Constants in C# help make code safer and more readable by giving fixed values meaningful names. When you understand const, readonly, and static readonly, you can choose the right form for compile-time values, object-level fixed values, and shared runtime values.


Continue learning C# in order
Follow the topic sequence with the previous and next lesson.