Search code examples
c#enumsdatamodel

Handling alphabetic enumerated codes in a database field


I have a field in a database (whose schema I can't change) which contains a specific set of values. Let's call them H, M, and L. H stands for High, M for Medium, and L is for Low. In C# I'd like to be able to reference these values in a typesafe way, but one that is also readable in code.

Currently there's a lot of this pattern littering the repository:

public static class Priority
{
    public const string High = "H";
    public const string Medium = "M";
    public const string Low = "L";
}

Which does provide the readability but isn't typesafe and could potentially be dangerous if lowercase values make their way into the database (unlikely but not impossible).

Is there a better way to handle this pattern?


Solution

  • You can implement this as a combination of an enum and a static class encapsulating logic for it, like this:

    public enum Priority { High, Medium, Low }
    
    public static class Priorities {
        public static string GetCode(this Priority priority) {
            switch (priority) {
            case Priority.High: return "H";
            case Priority.Medium: return "M";
            case Priority.Low: return "L";
            }
            throw new ArgumentException("priority");
        }
        public static Priority GetPriority(string priorityCode) {
            switch (priorityCode) {
            case "H": return Priority.High;
            case "M": return Priority.Medium;
            case "L": return Priority.Low;
            }
            throw new ArgumentException("priorityCode");
        }
    }
    

    Now you can use Priorities.GetPriority(codeFromDatabase) to make an element of Priority enumeration from a DB code, and call

    priority.GetCode()
    

    to obtain a code for writing a Priority back to the database.