Differences between Enums in C # and VB.NET

We have outdated character codes that we want to store as numbers in the new system. To increase readability and a general understanding of the code for developers doing the migration, I want to make Enums like this ...

Public Enum Status As Short
    Open = AscW("O")
    Closed = AscW("C")
    Pending = AscW("P")
    EnRoute = AscW("E")
End Enum

With this setting, 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 they will be effective. However ... I am a VB.NET guy, but everyone wants to code in C #, so I need this structure in C #.

After Googling, I found that the overall .NET equivalent AscWis equal Convert.ToInt32("C"). When I try to use this operator in an enumeration, I get a constant expression compiler error.

How can I do this in C #? Is there a better way?

+5
source share
2 answers

A method call is not a constant expression. Try the following:

public enum Status { 
   Open = 'O',
   Closed = 'C',
   Pending = 'P',
   EnRoute = 'E'
}

The reason it AscWworks in VB is that it is an internal thing that the VB compiler understands and evaluates at compile time and is considered the compiler. Even in VB Convert.ToInt32will 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. [...] In constant expressions, the following constructions are allowed:

[...]

  • The following runtime functions:

    • Microsoft.VisualBasic.Strings.ChrW
    • Microsoft.VisualBasic.Strings.Chrif a constant value is between 0 and 128
    • Microsoft.VisualBasic.Strings.AscWif the constant string is not empty
    • Microsoft.VisualBasic.Strings.Ascif the constant string is not empty
+10

:

public enum Status
{
    Open    = 'O',
    Closed  = 'C',
    Pending = 'P',
    EnRoute = 'E'
}
+3

All Articles