Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement C# enum for enumerated char(1) database field?

Tags:

c#

ascii

byte

OK, so I have a database field of type char(1) that has a small number of possible state codes (e.g. 'F'= Failure, 'U'=Unknown, etc.). I'd like to have a C# enum class that corresponds to these states. I can do:

public enum StatusCode : byte {
    Unknown = (byte) 'U',
    Failure = (byte) 'F',
    // etc.
}

So far so good. But in the DataTable returned from the database, the column values are System.Data.SqlTypes.SqlString instances. There are obviously some issues converting from a C# string (or even a C# char) to a C# byte (since C# char is really a UTF-16 codepoint). But in this case I know the values are constrained to a small set, and the code should throw an exception if a value outside this set comes through.

With that in mind, what's the best way of doing this? Is it safe to cast from a SqlString to a byte? Would Convert.ToByte() be better? Would it be better to simply use a switch/case construct to crosswalk the values into the enum?

I'm looking for the "best" way to do this, not only in terms of getting the right results but also for code clarity. I suppose I could also just use some constants like

public const char UnknownStatus = 'U';
public const char FailureStatus = 'F';

But I'd rather use an enum if possible. Any thoughts?

Edit: To clarify what I want do do with this, I'm expecting to use these values frequently throughout my code. For example, I want to be able to do things like:

public void DoSomething(StatusCode currentStatus) {
    if(currentStatus == StatusCode.Failure) {
        throw new SomeException();
    }

    switch(currentStatus) {
        case StatusCode.Unknown:
            // do something
            break;
    }
}

And so forth. I particularly want to avoid things like:

public void DoSomething(char currentStatus) {
    if(currentStatus == 'F') {
        // do something
    }
}

Since in this case I'm using what amounts to "magic numbers" all over the place. In particular, this would make migrating to some other state-flagging system virtually impossible. Does that make sense?

like image 856
Daniel Pryden Avatar asked Jul 24 '09 21:07

Daniel Pryden


1 Answers

Maybe a "constant" object?

public sealed class StatusCode {
    private char value;

    public static readonly StatusCode Unknown = new StatusCode('U');
    public static readonly StatusCode Failure = new StatusCode('F');

    private StatusCode(char v) {
        value = v;
    }

    public override string ToString() {
        return value.ToString();
    }

}

Then, later in your code, you could use it like an enum: StatusCode.Unknown. You could also provide an internal method to 'parse' a received value into an object of StatusCode.

like image 193
Fernando Avatar answered Sep 29 '22 06:09

Fernando