Const vs readonly
In C# when you want to have a named constant you have a choice between ‘const’ and ‘readonly’. For example:
public const string FooConst = "Bar"; public static readonly string FooReadonly = "Bar";
Which is appropriate?
Assembly Recompilation
You should only ever use ‘const’ on private fields. Using ‘const’ on a public field means that constant must be compiled into any consuming assembly. You might ask why having a constant compiled into consuming assemblies is a problem: The issue is that if you change that field, all consuming assemblies must be recompiled. Using ‘static readonly’ will not require consuming assemblies to be recompiled.
Flexibility/Mutability
Using ‘const’ is only possible with primitives, other value types, and strings, as its value is burned directly into the assembly. ‘Readonly’ on the other hand has no restrictions whatsoever, since it’s just a one time allocation of memory that has measures in place to prevent modification.
Also important to note is that ‘readonly’ only prevents the reference from being modified, not the actual memory being pointed to by the reference. To illustrate, the following is legal:
public class Foo { public static readonly IList<string> barReadonly = new List<string>(); public static void AppendString(string newString) { barReadonly.Add(newString); } }
Run time vs Compile time
A ‘const’ must be initialized immediately in code, and is initialized at compile time. A ‘readonly’ can be initialized at runtime, so long as it’s taken care of before the ctor exits.
Summary
In general, use ‘const’ when you know for certain that a value will never change, ever, or if the value is private. Otherwise, use ‘static readonly’.
Posted: June 5th, 2011 | Author: benlakey | Filed under: benlakey.com | Tags: .NET, C# | No Comments »
Leave a Reply