开发者

Can a C# enum entry have a hyphen in the name

Is thre any way to have an enum entry with a hyphen, "-", in the name, for example:

enum myEnum
{
   ok,
   not-ok,
}

I've seen the question about enums having friendly names however it would save me a bit of work if I can use a hyphen directly.

Update: The reason I want to use a hyphen is it makes it easy to use an enum for lists of set values which I have no control over such as:

 rejected
 replaced
 lo开发者_StackOverflow社区cal-bye
 remote-bye


No, a hyphen is not allowed.

Identifiers

You could obviously replace the hyphen with an underscore, but as @benPearce suggested, CamelCase would be a better choice, and in line with most C# coding standards.


Suppose you have:

enum E { a = 100 , a-b = 200 };
...

E b = E.a;
int c = (int)(E.a-b);

Is c set to 200, or 0 ?

Allowing hyphens in identifiers would make the language almost impossible to analyze lexically. This language is already hard enough to analyze what with << and >> each having two completely different meanings; we don't want to make it harder on ourselves.

The naming guidelines say to use CamelCasing for enum values; follow the guidelines.


In case somebody needs to use hyphens I think this approach can help: Use underscore in your enum declaration and then replace the underscore with hyphen.

enum myEnum { ok, not_ok, }

var test = myEnum.not_ok;
// let's say this value is coming from database or somewhere else
var someValue = "not-ok"; 

if(test.ToString().Replace("_","-").equals(someValue)) { /* some stuff */ }

Not the best practice, but can help if you don't have control over "someValue" and need to use enums.


You say "I'd happily follow the guidelines but the string list the enum is needed to represent is out of my control". Since this is why you want hyphens, I suggest you override the toString() method of the enums you need this for, and call toString() in your code where you need to represent the names.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜