0
enum ValidationMessages
{
    C01_OOHArrestRequired = "Test",
    Trivial,
    Regular,
    Important,
    Critical
};

I have the above code. I want to be able to create enums which I can use but are strings not integers.

This is so I can show same string in the UI for validation errors and then test for them in my unit tests and have the messages coming from the same place (been static).

But it says "Cannot convert string to int"

How to have enum as strings?

ekad
  • 14,436
  • 26
  • 44
  • 46
Lemex
  • 3,772
  • 14
  • 53
  • 87

4 Answers4

3

You cannot have an enum of type string, as enums are value types (byte, sbyte, short, ushort, int, uint, long, or ulong).

Instead create a static class with const fields:

public static class CardiologyValidationMessages
{
    public const string C01_OOHArrestRequired = "OOH Arrest is required when 1 or more Procedures Performed has IsCoronary = True"
}
Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
1

You can't. From MSDN:

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

What you can do is have a dictionary that maps an enum to an error message: Dictionary<CardiologyValidationMessages, string>

dcastro
  • 66,540
  • 21
  • 145
  • 155
1

"An enumeration is a set of named constants whose underlying type is any integral type"

However, you could write a conversion function.

string ToValidationMessageString(ValidationMessage value)
{
    switch(value)
    {
        case C01_OOHArrestRequired:
            return "Test";

        default:
            return value.ToString();
    }
}

or some such.

Jodrell
  • 34,946
  • 5
  • 87
  • 124
0

Anyone know how to have enum as strings?

You cannot.

From the C# Language Specification Version 5 (supplied with Visual Studio 2013) section 4.1.9

An enumeration type is a distinct type with named constants. Every enumeration type has an underlying type, which must be byte, sbyte, short, ushort, int, uint, long or ulong.

However you can apply an DisplayAttribute with a name to the values of the enumeration and then use the usual reflection methods to get the name for a given value.

Richard
  • 106,783
  • 21
  • 203
  • 265