C# – Enum-like class

cconstantsnetstatic-membersstring

I am looking for a best practice on how to create enum-like class that instead of numbers contains string values.
Something like this:

public static class CustomerType
{
  public static string Type1 = "Customer Type 1";
  public static string Type2 = "Customer Type 2";
}

I would use this class throughout application as a value for all cases where I need CustomerType. I cannot use Enum because this is legacy system, and values like this are hardcoded everywhere, I am just trying to centralize them in one place.

Question is, in above example, should I use for declaring a variable:

  1. static read-only keyword
  2. const keyword
  3. or just static

What would be a best practice to set these kinds of classes and values?

Best Answer

You should not use plain static because the fields could be inadvertently modified and cause mysterious breakage. Therefore, your two choices are static readonly and const.

const will cause the variable's value to be embedded in the calling code at compile-time, which would be effectively equivalent to the old hardcoded code (but with the advantage of a symbolic constant). The danger of const is that you must recompile everything if a const changes, lest you end up with out-of-sync constants and tricky bugs.

static readonly will result in a normal field access, so you won't have synchronization issues. However, you may take a slight performance hit due to the extra field access (though it is likely to be unnoticeable unless you use these fields a lot in performance-critical code). If you think you will have to change the strings at some point in the future, you will want to use static readonly.

From the sounds of it, the values will change rarely enough that const is a safe bet. However, the ultimate decision is up to you.