More fun with constants

In How constant is a constant?, I explained how constant values are hoisted from the .NET assembly they’re defined in and at compile time “baked in” to the assembly that references them. The result is that constants are forever. If the value of that constant ever changes then the referencing assembly will have the incorrect value unless that referencing assembly is recompiled.

C# 4.0 introduced Optional Arguments, a feature that has existed for years in many other languages. With optional arguments, you can write a method such as this:

public void MyMethod(int required, string optional = "default value")
{
    Console.WriteLine(optional);
}

You can then optionally include the optional parameter when you call the method:

MyMethod(1, "hello, world);    // outputs "hello, world"
MyMethod(1);    // outputs "default value"

Remember, though, that the default values you supply for your optional arguments are constants. If you change the default value to, say, “goodbye cruel world”, that changes the constant in the defining assembly, but the previous value is still stored in any programs that referenced the older version. You’ll have to recompile those programs in order to get the new default value.