Reputation: 82523
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?
Upvotes: 6
Views: 3321
Reputation: 422280
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
Upvotes: 11
Reputation: 57996
Try this:
public enum Status
{
Open = 'O',
Closed = 'C',
Pending = 'P',
EnRoute = 'E'
}
Upvotes: 3