Quite a few projects have one or more classes with with a bunch of public const string or public static readonly string values. Use const when things are really constant (like registry configuration keys), use static readonly when – upon change – I do not want to recompile dependent assemblies. Many people recommend static readonly over const.
Having members in stead of string literals scattered all over the place allows you to do compile timing checking, which I’m a big fan of as in the age of things getting more and more dynamic, you need to have as many sanity checks as possible.
One of the checks is to verify these const members and their values. Sometimes you need the list of members, sometimes the list of values, and sometimes each member value should be the same as the member name.
The listing below shows the code I came up with.
It works with code like this, and those can have more code and other fields (non string, non public) in them as well:
namespace bo.Literals { public class FooBarPublicStringConstants { public const string Foo = "Foo"; public const string Bar = "Bar"; } public class FooBarPublicStaticReadOnlyStringFields { public static readonly string Foo = "Foo"; public static readonly string Bar = "Bar"; } }
I started out with this code, but that is limited to classes only having public const fields. Not flexible enough. Read the rest of this entry »