Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a special char in a C# enum?

For example:

public enum Unit{
  KW,
  kV,
  V,
  Hz,
  %V
}

In this case % is a special character. So, how can I put this char in a enum?

like image 457
Edumenna Avatar asked Mar 03 '10 18:03

Edumenna


People also ask

Can we use special character in variable in C?

The C rule of declaring variable name says that variable name starts with the underscore but not with other special characters, but $ can also be used right.

How do you use special characters?

Alt Codes – How to Type Special Characters and Keyboard Symbols on Windows Using the Alt Keys. In Windows, you can type any character you want by holding down the ALT key, typing a sequence of numbers, then releasing the ALT key.


2 Answers

Even if you could do that (and it looks you can't), it probably wouldn't be a good idea, because you'd be mixing how the enum should be displayed with the program code to manipulate it. A better option would be to define an attribute (or use existing DisplayNameAttribute) and annotate your enum with names as additional meta-data:

public enum Unit{ 
  [DisplayName("Hz")] Hertz, 
  [DisplayName("%V")] Volt 
} 
like image 70
Tomas Petricek Avatar answered Oct 07 '22 13:10

Tomas Petricek


Enum members shouldn't be used for user interface display purposes. They should be mapped to a string in order to get displayed. You can create a string array (or a dictionary) that maps each enum member to a string for user interaction.

That said, to answer your question directly, you can use \uxxxxV were xxxx is the hexadecimal number representing the Unicode code point for %. This is far from recommended. As Henk points out, this won't work for % as it's not in Unicode classes Lu, Ll, Lt, Lm, Lo, Nl, Mn, Mc, Nd, Pc, Cf (letters, digits, connecting, and formatting characters). Only these characters are acceptable for identifiers.

like image 44
mmx Avatar answered Oct 07 '22 11:10

mmx