Tuesday, 16 October 2012

What is the difference between const and static readonly?

The value of a static readonly field is set at runtime; therefore, the value can be modified by the containing class. On the other hand, the value of a const field is set to a compile-time constant.

In the case of static readonly, the containing class is allowed to modify the value only:
  • in the variable declaration (via a variable initializer)
  • in the static constructor (or instance constructors for non-static)
Typically, static readonly is used either when the value is unknown at compile time or if the type of the field is not allowed in a const declaration.
Also, instance readonly fields are allowed.

Note: for reference types, in both cases—static and instance—the readonly modifier only prevents assignment of a new reference to the field. It does not specifically make the object pointed to by the reference immutable.
class TestProgram
   public static readonly Test test = new Test();
   static void Main (string[] args)
      test.Name = "Application";
      test = new Test();  
      // Error: A static readonly field cannot
      // be assigned to (except in a static constructor
      // or a variable initializer).  
class Test
   public string Name;
On the other hand, if Test were a value type, then assignment to test.Name would be an error.
Post a Comment