简体   繁体   中英

Is it possible to define an enum in C# with values that are keywords?

I have some client data that I am reading in, and I've defined an Enum for one of the values, so I can use Enum.Parse(type, somestring).

The problem is they just added a new value: "public". Is it possible to define an enum value that is also a reserved word?

IE:

public enum MyEnum {
    SomeVal,
    SomeOtherVal,
    public,
    YouGetTheIdea
}

If not I guess I'll be writing a parse method instead.

You can prepend a @ to the variable name. This allows you to use keywords as variable names - so @public .

See here .

From the C# spec :

The prefix "@" enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an @ prefix is called a verbatim identifier. Use of the @ prefix for identifiers that are not keywords is permitted, but strongly discouraged as a matter of style.

yes, prefix the name with an @. ie @public

If you capitalize public to Public it won't be recognized as a keyword. Keywords are case sensitive.

As a general practice, however, it's a bad idea to use names that are keywords (even when they differ by case) as it can cause confusions, or even subtle defects if the keyword is accidentally used in place of the identifier.

It's also possible to use the @ in certain contexts (like variable or member declarations) to use reserved words as non-keywords. However, it's not a common practice and should only be a means of last resort, when you can't use a different name.

So in your case you could also use @public to use the reserved word as an enum identifier.

If you chose to use @ , be aware that the symbol is only used in your source code to differentiate the identifier from the reserved word. To the outside world (and in methods like Enum.Parse() ), the name of the enum value is simply public .

For VB.NET do the following:

Public Enum MyEnum As Integer
    Disabled = 0
    [New] = 1
    [Public] = 2
    Super = 4
    [Error] = 5
End Enum

It's not really a great idea to do this though. Instead, add a bit more info to the enum:

PublicAccess etc

In VB.Net use square braces [...] to delineate a keyword as an identifier. Example:

Public Sub Test(ByVal [public] As String)
  MessageBox.Show("Test string: " & [public])
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM