3

I have a quick question regarding the use of "default" as an enum value. I'm reading the contents of an existing XML file and parsing the element values to enums. Here is and example of what is in the XML file:

<userpref_load_policy>default</userpref_load_policy>

Unfortunately I cannot do the following as 'default' is a keyword! 'at_start' and 'in_background' are the other permitted values for this element.

public enum LoadPolicy { default, at_start, in_background }

Is there an "easy" way to use default as an enum value or trick the compliler? I have a nasty feeling I will need to resort to a custom extension method. I say this as I'm calling the .ToString() method when writing the XML file back out (and there are lots of enums..)

Thanks in advance for any pointers, Iain

2

2 Answers 2

3

Yes, you can use it as an identifier using @:

public enum LoadPolicy { @default, at_start, in_background }

From the C# 5 spec, section 2.4.2:

The rules for identifiers given in this section correspond exactly to those recommended by the Unicode Standard Annex 31, except that underscore is allowed as an initial character (as is traditional in the C programming language), Unicode escape sequences are permitted in identifiers, and the "@" character is allowed as a prefix to enable keywords to be used as identifiers.

I would personally prefer to use more idiomatic names within the enum itself, but have a mapping between the enum values and their XML representations. But this will work if you really have to use the enum value names...

Sign up to request clarification or add additional context in comments.

4 Comments

Jon is correct but I believe it is standard practice to have your default enum value be "none" which is more meaningful.
@BenRobinson: It depends on the situation. This is one of those "rules" that shouldn't be applied too dogmatically, IMO... and is much more applicable to flags enums than non-flags ones. (As I've said in the answer, I would take a different approach to this anyway, but...)
*&^% that was quick! Thanks Jon, my Google-foo had failed me. Easy when you know how :)
@BenRobinson: Point taken. However, in my situation there are only 3 available values; one just happens to be 'default' and 'none' is not an option!
1

Any keyword can be escaped using an @:

public enum LoadPolicy { @default, at_start, in_background }

The @ is just a marker; not really part of the name. So later when you use it can just write:

LoadPolicy x = LoadPolicy.default;

The @ is only needed when the meaning is ambiguous.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.