Home ยป C# Constants : A Tutorial

C# Constants : A Tutorial

by wskandot71

Constants in C# are variables whose values cannot change after assignment. They provide a way to define fixed values that remain the same throughout the program execution.

Constants improve code readability, maintainability, and prevent accidental modifications.

This tutorial covers:

  • What are Constants in C#
  • Declaring Constants with const
  • Constant Data Types
  • Using Constants in Expressions
  • Difference Between const and readonly
  • Best Practices for Using Constants

1. What Are Constants in C#?

A constant in C# is a variable that holds a fixed value that cannot be modified once assigned. Constants are declared using the const keyword.

Example: Declaring a Constant

const double Pi = 3.14159;
Console.WriteLine(Pi); // Output: 3.14159
  • The value of Pi remains unchanged throughout the program.
  • Attempting to modify Pi will result in a compilation error.

2. Declaring Constants with const

A constant is declared using the const keyword, followed by the data type and constant name.

Syntax:

const dataType constantName = value;

Example: Different Constant Types

const int MaxRetries = 5;
const double Gravity = 9.81;
const string AppName = "MyApplication";
const char Grade = 'A';
const bool IsActive = true;
  • MaxRetries holds an integer.
  • Gravity holds a floating-point number.
  • AppName stores a string.
  • Grade stores a single character.
  • IsActive holds a Boolean value.

3. Constant Data Types

Constants can be of primitive data types, including:

  • int
  • double
  • float
  • decimal
  • char
  • bool
  • string

Example: Constant with decimal (For Financial Calculations)

const decimal TaxRate = 0.18m;
Console.WriteLine($"Tax Rate: {TaxRate * 100}%"); // Output: Tax Rate: 18%
  • decimal is recommended for financial calculations due to higher precision.

4. Using Constants in Expressions

Constants can be used in expressions, including mathematical calculations and string concatenation.

Example: Constants in a Calculation

const double Pi = 3.14159;
const double Radius = 5;
double area = Pi * Radius * Radius;
Console.WriteLine($"Area of Circle: {area}");

Example: Constants in String Concatenation

const string FirstName = "John";
const string LastName = "Doe";
const string FullName = FirstName + " " + LastName;
Console.WriteLine(FullName); // Output: John Doe

5. Difference Between const and readonly

C# provides two ways to define non-modifiable variables:

  • const (Compile-time constant)
  • readonly (Run-time constant)

Key Differences

Feature const readonly
Value Assignment Assigned at declaration Assigned at runtime (constructor)
Modifiable Cannot change Can change only in the constructor
Scope Always static Instance or static
Performance Faster (Replaced at compile-time) Evaluated at runtime

Example: Using const

const int MaxUsers = 100;
// MaxUsers = 200; // ERROR: Cannot modify a constant

Example: Using readonly

class Config
{
    public readonly int MaxUsers;

    public Config(int value)
    {
        MaxUsers = value; // Allowed in constructor
    }
}

Config config = new Config(200);
Console.WriteLine(config.MaxUsers); // Output: 200
  • readonly allows values to be set at runtime, whereas const must be assigned at declaration.

6. Best Practices for Using Constants

Use Uppercase Naming Convention for Constants

const double PI = 3.14159;
const int MAX_ATTEMPTS = 3;
  • Constants should be in uppercase with words separated by underscores.

Use const for Fixed Values

const string APP_NAME = "MyApplication"; // Suitable for constant values

Use readonly for Values That Can Change at Runtime

class Settings
{
    public readonly string ConfigPath;

    public Settings(string path)
    {
        ConfigPath = path; // Can be set at runtime
    }
}

Use decimal for Financial Constants

const decimal VAT_RATE = 0.20m;
  • decimal provides better precision for financial values.

Avoid Hardcoding Constants in Multiple Places

// Instead of repeating
const int BUFFER_SIZE = 1024;

// Use a central Constants class
public static class Constants
{
    public const int BUFFER_SIZE = 1024;
}
  • This approach avoids duplication and makes maintenance easier.

7. When to Use const vs readonly

Use const When:

  • The value is always fixed (mathematical constants, application settings).
  • Performance is critical (compile-time evaluation).
  • The value is not dependent on external inputs.

Use readonly When:

  • The value might change at runtime but should remain constant after assignment.
  • You need instance-specific values (e.g., configuration settings).
  • The value is derived from external sources (e.g., a database or user input).

8. Common Mistakes to Avoid

Declaring Non-Primitive Data Types as const

// ERROR: Cannot declare an array as const
const int[] Numbers = { 1, 2, 3 }; // Not allowed
  • Arrays, lists, and objects cannot be declared as const.

Using const When Value Might Change Later

// If the tax rate can change, use readonly instead of const
const decimal TAX_RATE = 0.18m; // Use readonly if it can change

Modifying a Constant Value

const int MAX_RETRIES = 3;
// MAX_RETRIES = 5; // ERROR: Cannot modify a constant
  • Once assigned, constants cannot be changed.

Conclusion

  • Constants (const) store fixed values that do not change after assignment.
  • Constants improve code readability and prevent accidental modifications.
  • Use readonly when values need to be set at runtime.
  • Constants are always static and should be declared using uppercase naming conventions.
  • Best practices help ensure maintainability and prevent common mistakes.

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.