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?
A method call is not a constant expression. Try this:
The reason
AscWworks 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.ToInt32will not work.To quote the Visual Basic specification: