Language: EN

csharp-que-son-constantes

What are and how to use constants in C#

A constant is an identifier used to represent a constant and predefined value that does not change during the execution of the program.

Constants are used to avoid the repetition of literal values in the code and improve its clarity and readability.

Moreover, using constants facilitates the updating and maintenance of the code, as if you need to change the value of a constant, you only need to do it in one place.

Syntax of constants

The basic syntax for defining a constant in C# is as follows:

public const type name = value;
  • type: Specifies the data type of the constant
  • name: Is the unique name given to the constant
  • value: Is the constant value assigned to the constant

For example, let’s see how we can define a constant with the value of PI.


public const double PI = 3.14159;


Console.WriteLine(PI); // Output: 3.14159

PI = 3.5; // ❌ this would give an error, you cannot reassign a constant

Using constants

Accessing constants

Constants are accessed using the class name followed by the constant name.

Console.WriteLine(Constants.Pi);

Using in expressions

Constants can be used in expressions instead of literal values to improve the readability and clarity of the code.

double area = Constants.Pi * radius * radius;

Naming convention

It is not mandatory, but it is relatively common to use uppercase names for constants to distinguish them from other variables.

public const double PI = 3.14159;

Readonly variables

Readonly variables (readonly) are similar to constants, but their value can be assigned or changed in the class constructor. Once assigned, their value cannot change. This is useful for defining constants that need to be calculated at runtime or initialized in the constructor.

public class Example
{
    public readonly int number;

    public Example(int value)
    {
        number = value;
    }
}

In this example, number is a readonly variable that can be assigned in the constructor but cannot be modified afterward.

Practical examples

Defining mathematical constants

public class MathematicalConstants
{
    public const double Pi = 3.14159;
    public const double Euler = 2.71828;
}

Defining configuration constants

public class Configuration
{
    public const int MaxLoginAttempts = 3;
    public const string DateFormat = "dd/MM/yyyy";
}