How to use const, readonly, and static in C#

By FoxLearn 1/6/2025 3:59:25 AM   86
The const, readonly, and static keywords in C# are frequently used but have distinct roles with some similarities that can make their usage confusing.

Using the const Keyword in C#

The const keyword in C# is used to define a constant variable, meaning its value cannot be changed throughout the program's execution. A value must be assigned to a constant at the time of its declaration, making it a "compile-time" constant.

For example, using const in C#:

const double pi = 3.14159;

This declares a constant pi with a value that will not change during the program's runtime.

The const keyword is limited to primitive data types (e.g., int, float, char, bool, and string). You cannot use const to create constant objects, as object instances are not considered compile-time constants.

For example, consider the following class Book:

public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
}

Trying to create a constant object like this:

const Book myBook = new Book { Id = 1, Title = "C# Basics", Author = "John Doe" };

Would result in a compilation error, because the new Book() expression is not a constant value and thus cannot be assigned to a const variable.

Using the readonly keyword in C#

The readonly keyword in C# is used to define a variable or object that can only be assigned a value once, either at the time of declaration or within a constructor. After that, the value cannot be changed in any other method or part of the class. This makes readonly ideal for values that should remain constant after initialization but may need to be set dynamically during object construction.

For example, consider the following Person class:

public class Person
{
    public readonly string Name;
    public readonly int Age;

    public Person(string name, int age)
    {
        Name = name; // Can be assigned in the constructor
        Age = age;   // Can be assigned in the constructor
    }

    public void ChangeDetails()
    {
        Name = "New Name";  // This will cause a compile-time error
    }
}

In the above example, the Name and Age properties are marked as readonly. They can be assigned values only inside the constructor. Any attempt to modify these values outside the constructor (like in the ChangeDetails method) will result in a compilation error, as readonly variables cannot be reassigned outside of their initial assignment in the constructor.

Using the static keyword in C#

The static keyword in C# can be applied to variables, methods, or objects to indicate that they belong to the class type rather than to instances of the class. This means that static members are accessed through the class name itself, not through an object of the class.

For example, consider the following class MathUtility that contains a static method:

public class MathUtility
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

You cannot call the Add method using an instance of the MathUtility class.

int result = MathUtility.Add(5, 3);

This rule applies to static variables and objects as well. Static members are accessed directly through the class, not through an instance.

For example, if you had a static variable:

public class Counter
{
    public static int Count = 0;
}

You would access the static variable like this:

Counter.Count++;

A class can also have a static constructor, which is used to initialize static members.

However, a static constructor cannot accept parameters:

public class Configuration
{
    public static string ConfigSetting;

    static Configuration()
    {
        ConfigSetting = "Default Configuration";
    }
}

The rule of thumb for using const, readonly, and static is:

  • Use const when a value will never change throughout the application's lifetime.
  • Use readonly when the value may be set once (e.g., in a constructor) but should not be modified afterwards by other parts of the program.
  • Use static when you want a member to belong to the class itself, rather than to an instance of the class.