We have legacy character codes that we want to store as numbers in a new system. To increase readibility and general understanding in the code for devs making the migration, I want to do Enums like this...
Public Enum Status As Short
Open = AscW("O")
Closed = AscW("C")
Pending = AscW("P")
EnRoute = AscW("E")
End Enum
With this setup, the code will be readable (imagine If Record.Status = Status.Open
), and yet the values will be stored in the database as small numbers so it will be efficient. However... I am a VB.NET guy, but everybody wants to code in C#, so I need this sort of structure in C#.
After Googling, I discovered the the general .NET equivalent of AscW
is Convert.ToInt32("C")
. When I try to use that statement in an enum, I get the compiler error "Constant Expression Required".
How can I do this in C#? Is there a better way?
The use of an enumeration constant (enum) has many advantages over using the traditional symbolic constant style of #define. These advantages include a lower maintenance requirement, improved program readability, and better debugging capability.
One of the differences between the two is that #define is a pre-processor directive while enum is part of the actual C language. #define statements are processed by the compiler before the first line of C code is even looked at!
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.
Enum is to define a collection of options available. A struct can contain both data variables and methods. Enum can only contain data types. A struct supports a private but not protected access specifier.
A method call is not a constant expression. Try this:
public enum Status {
Open = 'O',
Closed = 'C',
Pending = 'P',
EnRoute = 'E'
}
The reason AscW
works in VB is that it's an internal thing that VB compiler understands and evaluates at compile time and is considered a constant expression by the compiler. Even in VB, Convert.ToInt32
will not work.
To quote the Visual Basic specification:
11.2 Constant Expressions
A constant expression is an expression whose value can be fully evaluated at compile time. [...] The following constructs are permitted in constant expressions:
[...]
The following run-time functions:
Microsoft.VisualBasic.Strings.ChrW
Microsoft.VisualBasic.Strings.Chr
, if the constant value is between 0 and 128Microsoft.VisualBasic.Strings.AscW
, if the constant string is not emptyMicrosoft.VisualBasic.Strings.Asc
, if the constant string is not empty
Try this:
public enum Status
{
Open = 'O',
Closed = 'C',
Pending = 'P',
EnRoute = 'E'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With