What's the difference between 'Enum : Type' and simply 'Enum'

.net, c#, enums

Solution

It dictates the underlying type that will be used for storage of the enumeration.

When you use `enum` without anything else, it uses an `int` as 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:

The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

If you want to store `char` values, then you have two options.

You could use an underlying type of `ushort` (it's an unsigned 16-bit integer like `char`), like so:

public enum AuditInteractionTypes : ushort
{
    Authorized = 'A',
    Created = 'C',
    Revised = 'R',
    Extracted = 'E',
    Deleted = 'D'
}

`char` has an implicit conversion to `ushort` so 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:

public static class AuditInteractionTypes
{
    // You can make these static readonly if they are likely to change.
    public const string Authorized = "A";
    public const string Created = "C";
    public const string Revised = "R";
    public const string Extracted = "E";
    public const string Deleted = "D";
}

This class will then pretty much look the same as an `enum` and code the same way.

Note, the same trick can be done with any type, but generally those types should be completely immutable. `string` fills this guideline nicely, being completely immutable (as are most system value types, and other value types, if you've designed them correctly).

Problem

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.

Original source