I am trying to understand a few things about Enums in general and how they can work with Chars specifically. Below is my example I am working from:
public enum AuditInteractionTypes
{
Authorized = 'A',
Created = 'C',
Revised = 'R',
Extracted = 'E',
Deleted = 'D'
}
First, what’s the difference between declaring them enum AuditInteractionTypes or enum AuditInteractionTypes : char
Second, I have seen the numerous post’s about trying to use Enums with chars and how to “make” it work back and forth. Possible stupid question but why couldn’t I simply go back and forth as a string.
So, for example, Authorized = "A".
I have am using Linq To SQL as my DAL if that matters though I am asking, I hope, a broader level question not specific to my environment.
It dictates the underlying type that will be used for storage of the enumeration.
When you use
enumwithout anything else, it uses anintas the underlying storage type.When you use
enum : <type>, it uses that type as the underlying storage type.In your case, you’re trying to make the underlying type of type
char, but that’s not valid, according to the C# reference:If you want to store
charvalues, then you have two options.You could use an underlying type of
ushort(it’s an unsigned 16-bit integer likechar), like so:charhas an implicit conversion toushortso the above works. Also, you can easily compare the two.If you want to use a string as the value then I’d recommend an
enum-like class, like so:This class will then pretty much look the same as an
enumand code the same way.Note, the same trick can be done with any type, but generally those types should be completely immutable.
stringfills this guideline nicely, being completely immutable (as are most system value types, and other value types, if you’ve designed them correctly).