What is the difference between const and static readonly?

When dealing with constants in C#, it’s essential to understand the difference between static readonly and const fields. Both are used to represent values that shouldn’t change during the program’s execution, but they have distinct characteristics.

const Fields

  • const fields are set to a compile-time constant and cannot be modified afterward.
  • They are implicitly static and are implicitly readonly.
  • The value must be known at compile time.
  • const fields are implicitly static, meaning they belong to the type rather than an instance.
  • They are set during compilation and can’t be changed at runtime.
  • Commonly used for primitive types and strings.
class Program
{
    public const int MaxValue = 100;

    static void Main(string[] args)
    {
        // Error: A constant value cannot be modified
        // MaxValue = 200; 
    }
}

static readonly Fields

  • static readonly fields are set at runtime and can be modified only in the variable declaration or within the static constructor (or instance constructors if not static).
  • They are used when the value is not known at compile time or when the type of the field is not allowed in a const declaration.
  • Commonly used for non-primitive types.
class Program
{
    public static readonly Test test = new Test();

    static void Main(string[] args)
    {
        // Error: A static readonly field cannot be assigned to
        // (except in a static constructor or a variable initializer)
        // test = new Test(); 
    }
}

class Test
{
    public string Name;
}

Important Note for Reference Types

For reference types, both static readonly and const fields prevent you from assigning a new reference to the field. However, they do not make the object pointed to by the reference immutable. Modifications to the object’s properties are still allowed.

Understanding when to use const and when to use static readonly depends on whether the value is known at compile time and the type of the field. Choose the appropriate approach based on your specific requirements.

Comments

Popular posts from this blog

How do I calculate a MD5 hash from a string?

What is WSDL?