c# - Enum-like class -
c# - Enum-like class -
i looking best practice on how create enum-like class instead of numbers contains string values. this:
public static class customertype { public static string type1 = "customer type 1"; public static string type2 = "customer type 2"; }
i utilize class throughout application value cases need customertype. cannot utilize enum because legacy system, , values hardcoded everywhere, trying centralize them in 1 place.
question is, in above example, should utilize declaring variable:
static read-only keyword const keyword or staticwhat best practice set these kinds of classes , values?
you should not utilize plain static
because fields inadvertently modified , cause mysterious breakage. therefore, 2 choices static readonly
, const
.
const
cause variable's value embedded in calling code @ compile-time, equivalent old hardcoded code (but advantage of symbolic constant). danger of const
must recompile if const
changes, lest end out-of-sync constants , tricky bugs.
static readonly
result in normal field access, won't have synchronization issues. however, may take slight performance nail due field access (though unnoticeable unless utilize these fields lot in performance-critical code). if think have alter strings @ point in future, want utilize static readonly
.
from sounds of it, values alter plenty const
safe bet. however, ultimate decision you.
c# .net string const static-members
Comments
Post a Comment