0

I have a database which needs a status column updating to a single char status code ('E' or 'U').

I'd like to use an enum for updating this field through my API to ensure the possible values are restricted correctly. Obviously enums can't be of char type. What might be be a good alternative method?

And no, I can't change the database schema :)

fearofawhackplanet
  • 52,166
  • 53
  • 160
  • 253
  • Looks similar to http://stackoverflow.com/questions/1180174/how-to-implement-c-enum-for-enumerated-char1-database-field - hoepfully that will help you. – Chris Jul 28 '10 at 11:27

2 Answers2

4

You can assign chars to enum members.

Does this help:

enum Status
{
 Empty = 'E',
 Updated = 'U'
}
void Main()
{
 Status status = Status.Empty;
 Console.WriteLine("{0}: {1}", status, (char)status);
}
Will Dean
  • 39,055
  • 11
  • 90
  • 118
  • Interesting, I did not realise the compiler allows this :) Thanks – leppie Jul 28 '10 at 11:29
  • Nor did I... The benefits of Linqpad! – Will Dean Jul 28 '10 at 11:30
  • I've seen this setup before, it seems a bit hacky to me and doesn't really ensure data integrity (you have to remember the cast). I might use it if there's nothing better available though. – fearofawhackplanet Jul 28 '10 at 12:16
  • If you forget the cast, will your data layer not complain about trying to assign the wrong type to that column/field? – Will Dean Jul 28 '10 at 12:25
  • At the moment it's just a stored procedure call. Wouldn't it just insert the char '0' or '1'? I don't actually know. – fearofawhackplanet Jul 28 '10 at 12:51
  • I certainly don't think it would do 0 or 1 - those values don't appear anywhere in the enum. You might get 69 or 85 in some way that you didn't want, I suppose. – Will Dean Jul 28 '10 at 12:54
1

byte - if you have char

ushort - if you have nchar

Both can be cast to the underlying integer, and then cast to char (C#).

leppie
  • 115,091
  • 17
  • 196
  • 297