How to Declare Constants in C# Using const

This article provides a direct guide on how to declare and use constant variables in C# using the const keyword. You will learn the exact syntax required for declaration, understand the mandatory rules and supported data types for compile-time constants, and review practical code examples demonstrating how to implement them properly in your applications.

Syntax for the const Keyword

To declare a constant in C#, place the const keyword before the data type, followed by the variable name and an immediate value assignment.

const data_type variable_name = value;

A constant must be initialized at the moment it is declared. If you attempt to declare a constant without assigning a value immediately, the C# compiler will generate an error (CS0145: A const field requires a value to be provided).

Basic Declaration Examples

Here is how to declare constants using various built-in data types:

public class ApplicationConstants
{
    // Numeric constants
    public const int MaxRetryAttempts = 3;
    public const double Pi = 3.141592653589793;
    public const decimal TaxRate = 0.075m;

    // String and character constants
    public const string ApplicationName = "TaskManager";
    public const char DefaultDelimiter = ',';

    // Boolean constant
    public const bool FeatureFlagEnabled = true;
}

Key Rules for Using const in C

When working with the const keyword, keep the following core behaviors in mind:

  1. Compile-Time Evaluation: Constant values are evaluated at compile time and hardcoded directly into the Intermediate Language (IL) wherever they are referenced. Because of this, their values must be determinable at build time.
  2. Restricted Data Types: Constants can only be primitive types (such as int, double, bool, char), string, or enum types. The only reference type other than string that can be declared as const is a reference set to null.
  3. Implicitly Static: When declared at the class level, constants are implicitly static. You do not—and cannot—use the static modifier with const. To access a class-level constant, call it using the class name rather than an instance of the class (e.g., ApplicationConstants.MaxRetryAttempts).
  4. Local Constants: The const keyword can also be used inside methods to create local, immutable variables scoped strictly to that method block.
public void CalculateTotal(decimal subtotal)
{
    const decimal LocalDiscount = 5.00m;
    decimal finalPrice = subtotal - LocalDiscount;
}

If you require an immutable value that is computed at runtime (such as using an object constructor or dynamic configuration), use the readonly modifier instead of const.