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 program’s execution.

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

In addition, the use of constants facilitates code updating and maintenance, 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

Use of constants

Accessing constants

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

Console.WriteLine(Constants.Pi);

Usage in expressions

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

double area = Constants.Pi * radius * radius;

Naming convention

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

public const double PI = 3.14159;

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 LoginAttemptsLimit = 3;
    public const string DateFormat = "dd/MM/yyyy";
}