Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

enums

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
 local-bye
 remote-bye
like image 408
sipsorcery Avatar asked Feb 24 '10 04:02

sipsorcery


2 Answers

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.

like image 162
Miguel Avatar answered Oct 10 '22 16:10

Miguel


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.

like image 36
Eric Lippert Avatar answered Oct 10 '22 16:10

Eric Lippert