Mobile Software Engineering

2008-10-13 by tamberg

Changing C# Constants

If we expose a constant value in a public (or internal) class we use the modifiers static readonly instead of const, to be able to change the value in the future. The C# Specification states that:

A constant is a class member that represents a constant value: a value that can be computed at compile-time. [...] constants are considered static members

Given a system with more than one assembly, this means that values are inserted in place at compileĀ­time of the client rather than looked up at run-time. Changing the constant thus has no effect on client assemblies until they are recompiled. Worse, without recompilation clients will not even notice that a const member has been entirely removed. Consider the following example:

// C.cs
		
public class C {
  public const int c = 7;
}

// P.cs

using System;

class Program {
  static void Main () {
    Console.WriteLine(C.c);
  }
}

Running the program P.exe outputs the string 7. After deleting public const int c = 7; from C.cs the output is still 7. Replacing const with static readonly in the above example leads to a System.MissingFieldException as soon as the client tries to access the deleted variable. Note, that such an exception is a good thing because the client code is already broken anyway.

Besides deleting constants there are many other types of breaking changes in .NET, but there seems to be no specification as to what exactly is considered breaking and what is not. The closest thing to a complete list of breaking changes in .NET can be found at the .NET BCL Team Blog.