tags:

views:

167

answers:

4

i have to create an enum that contains values that are having spaces

public enum MyEnum
        {
            My cart,
            Selected items,
            Bill            
        }

This is giving error. Using concatenated words like MyCart or using underscore My_Cart is not an option. Please guide.

Thanks in advance.

+4  A: 

From enum (C# Reference)

An enumerator may not contain white space in its name.

astander
is there any work-around to it ?
HotTester
Comments have been posted to your question regarding displaying the enum without the underscore, if you so wish.
astander
+2  A: 

Enum just cant have space! What do you need it for? If you need it simply for display purpose, you can stick with underscore and write an extension method for your enum so that you can ask for the display text by doing this (assuming your ext method is call DisplayText). Internally you just implement the DisplayText method to substitute "_" with space

MyEnum.My_Cart.DisplayText();   // which return "My Cart"
Fadrian Sudaman
+1  A: 

As per the C# specification, "An enumerator may not contain white space in its name." (see http://msdn.microsoft.com/en-us/library/sbbt4032.aspx) Why do you need this?

Will
enum is not an enumerator...
leppie
I didn't write the message, MS did, and I guess they made a typo! =) (the text i quoted is from the MS article I provided a link for)
Will
Quite interesting the msdn link says enum as enumerator ! A msdn bug ?
HotTester
Oops, sorry, I did note others using the same verbology.
leppie
A: 

I agree the use of DisplayText if you are following convention. But if you need different display value to represent the enum constant, then you could have a constructor passing that value.

public enum MyEnum { My cart ("Cart"), Selected items("All Selected Items"), Bill("Payment");

private String displayValue; 
private MyEnum(String displayValue) {

this.displayValue = displayValue; }
public String displayText() { return this.displayValue; }

}

You can have a displayText method or a toString method which would return the displayValue

hp
This doesn't compile - an Enum is simply a list of values, it cannot contain members, constructors, etc. The most you can do is assign a specific integer value to a constant, but even then you cannot use spaces in the constant names.
Andy Shellam