74

I want to set the space on my enum. Here is my code sample:

public enum category { goodBoy=1, BadBoy } 

I want to set

public enum category { Good Boy=1, Bad Boy } 

When I retrieve I want to see Good Boy result from the enum

4
  • It's not entirely clear what you're asking. Can you rephrase a bit? Commented Jul 9, 2009 at 4:47
  • On my enum "Good_Boy"set but on my control i want to replace _ with Space how to do Commented Jul 9, 2009 at 5:26
  • Which control do you want to set it on? It's important. Commented Jul 18, 2009 at 15:29
  • Possible duplicate of How to give enum values that are having space Commented Aug 29, 2016 at 19:50

19 Answers 19

108

You can decorate your Enum values with DataAnnotations, so the following is true:

using System.ComponentModel.DataAnnotations; public enum Boys { [Display(Name="Good Boy")] GoodBoy, [Display(Name="Bad Boy")] BadBoy } 

I'm not sure what UI Framework you're using for your controls, but ASP.NET MVC can read DataAnnotations when you type HTML.LabelFor in your Razor views.

Here's an Extension method

If you are not using Razor views or if you want to get the names in code:

public class EnumExtention { public Dictionary<int, string> ToDictionary(Enum myEnum) { var myEnumType = myEnum.GetType(); var names = myEnumType.GetFields() .Where(m => m.GetCustomAttribute<DisplayAttribute>() != null) .Select(e => e.GetCustomAttribute<DisplayAttribute>().Name); var values = Enum.GetValues(myEnumType).Cast<int>(); return names.Zip(values, (n, v) => new KeyValuePair<int, string>(v, n)) .ToDictionary(kv => kv.Key, kv => kv.Value); } } 

Then use it:

Boys.GoodBoy.ToDictionary() 
Sign up to request clarification or add additional context in comments.

4 Comments

namespace required for Description is System.ComponentModel
Jeah; using System.ComponentModel.DataAnnotations;
I think this namespace is available only in a web application, while the poster does not mention anywhere he's working with one.
I'm using the namespace it a WinForms class library project - I don't think it's ASP only
24

You are misunderstanding what an enum is used for. An enum is for programming purposes, essentially giving a name to a number. This is for the programmer's benefit while reading the source code.

status = StatusLevel.CRITICAL; // this is a lot easier to read... status = 5; // ...than this 

Enums are not meant for display purposes and should not be shown to the end user. Like any other variable, enums cannot use spaces in the names.

To associate internal values with "pretty" labels you can display to a user, can use a dictionary or hash.

myDict["Bad Boy"] = "joe blow"; 

3 Comments

On my enum "Good_Boy"set but on my control i want to replace _ with Space how to do
DON'T use enum names where the user can see. As I said before, use a dictionary. That's what they're built for. enums are for programming-level unification, NOT for user display!
The thing is often the datasource for a combobox is not defined in the datatabase, rather, its source is an enumeration. I am not sure this is a bad thing.
20

Based on Smac's suggestion, I've added an extension method for ease, since I'm seeing a lot of people still having issues with this.

I've used the annotations and a helper extension method.

Enum definition:

internal enum TravelClass { [Description("Economy With Restrictions")] EconomyWithRestrictions, [Description("Economy Without Restrictions")] EconomyWithoutRestrictions } 

Extension class definition:

internal static class Extensions { public static string ToDescription(this Enum value) { FieldInfo field = value.GetType().GetField(value.ToString()); DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; return attribute == null ? value.ToString() : attribute.Description; } } 

Example using the enum:

var enumValue = TravelClass.EconomyWithRestrictions; string stringValue = enumValue.ToDescription(); 

This will return Economy With Restrictions.

Hope this helps people out as a complete example. Once again, credit goes to Smac for this idea, I just completed it with the extension method.

Comments

17
using System.ComponentModel; 

then...

public enum category { [Description("Good Boy")] goodboy, [Description("Bad Boy")] badboy } 

Solved!!

2 Comments

Please don't just code dump. Provide an explanation about it, such as you can use attributes ... such as ... because ... example
Upvoted this answer since I'm working in the context of Unity, and the DataAnnotations are not available.
16

Think this might already be covered, some suggestions:

Just can't beat stackoverflow ;) just sooo much on here nowdays.

Comments

10

That's not possible, an enumerator cannot contain white space in its name.

Comments

4

Developing on user14570's (nice) workaround referred above, here's a complete example:

 public enum MyEnum { My_Word, Another_One_With_More_Words, One_More, We_Are_Done_At_Last } internal class Program { private static void Main(string[] args) { IEnumerable<MyEnum> values = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>(); List<string> valuesWithSpaces = new List<string>(values.Select(v => v.ToString().Replace("_", " "))); foreach (MyEnum enumElement in values) Console.WriteLine($"Name: {enumElement}, Value: {(int)enumElement}"); Console.WriteLine(); foreach (string stringRepresentation in valuesWithSpaces) Console.WriteLine(stringRepresentation); } } 

Output:

enter image description here

Comments

3

Why don't you use ToString() ?

I mean that when use ToString(),it gives the enum value. Just you have to add some identifier to catch space.For example:

public enum category { good_Boy=1, Bad_Boy } 

When you get an enum in codes like category a = ..., you can use ToString() method. It gives you value as a string. After that, you can simply change _ to empty string.

2 Comments

It's not about values. He wants to write as int x=(int)category.good Boy
A nice workaround. I developed your into a full example below.
3

I used Regex to split the values by capital letter and then immediately join into a string with a space between each string in the returned array.

string.Join(" ", Regex.Split(v.ToString(), @"(?<!^)(?=[A-Z])")); 

First get the values of the enum:

var values = Enum.GetValues(typeof(Category)); 

Then loop through the values and use the code above to get the values:

var ret = new Dictionary<int, string>(); foreach (Category v in values) { ret.Add((int)v, string.Join(" ", Regex.Split(v.ToString(), @"(?<!^)(?=[A-Z])"))); } 

In my case I needed a dictionary with the value and display name so that it why I have the variable "ret"

Comments

2

C# now has a built in function to get the description from an enum. Here's how it works

My Enum:

using System.ComponentModel.DataAnnotations; public enum Boys { [Description("Good Boy")] GoodBoy = 1, [Description("Bad Boy")] BadBoy = 2 } 

This is how to retrieve the description in code

var enumValue = Boys.GoodBoy; string stringValue = enumValue.ToDescription(); 

Result is : Good Boy.

5 Comments

Are you using the reference System.ComponentModel.DataAnnotations;
This is not working for me. Intellisense does not recognize ToDescription(). I tried using System.ComponentModel.DataAnnotations. What version of C# are you using? What library?
This is for sure more elegant than my solution, with the only drawback of having to maintain 2 list of values, one for the enumeration and one for its description...
@jshockwave, you could make an extension method for that. I've posted an example with that. Hope it helps.
.ToDescription() doesn't seem to exist. Perhaps this is referring to the code from this answer?
2

If you do not want to write manual annotations, you can use an extension method that will add spaces to the enum's names:

using System.Text.RegularExpressions; public static partial class Extensions { public static string AddCamelSpace(this string str) => Regex.Replace(Regex.Replace(str, @"([^_\p{Ll}])([^_\p{Ll}]\p{Ll})", "$1 $2"), @"(\p{Ll})([^_\p{Ll}])" , "$1 $2"); public static string ToCamelString(this Enum e) => e.ToString().AddCamelSpace().Replace('_', ' '); } 

You can use like this:

enum StudentType { BCStudent, OntarioStudent, badStudent, GoodStudent, Medal_of_HonorStudent } StudentType.BCStudent.ToCamelString(); // BC Student StudentType.OntarioStudent.ToCamelString(); // Ontario Student StudentType.badStudent.ToCamelString(); // bad Student StudentType.GoodStudent.ToCamelString(); // Good Student StudentType.Medal_of_HonorStudent.ToCamelString(); // Medal of Honor Student 

See on .NET fiddle

Comments

1
public enum MyEnum { With_Space, With_Two_Spaces } //I store spaces as underscore. Actual values are 'With Space' and 'With Two Spaces' public MyEnum[] arrayEnum = (MyEnum[])Enum.GetValues(typeof(MyEnum)); string firstEnumValue = String.Concat(arrayEnum[0].ToString().Replace('_', ' ')) //I get 'With Space' as first value string SecondEnumValue = String.Concat(arrayEnum[1].ToString().Replace('_', ' ')) //I get 'With Two Spaces' as second value 

Comments

1

Retrieving enum value is pretty complicated to me, while enum value is different than its name. For this purpose, I would like to use a class with const fields and a list that contains all of these fields. Using this list, I could check later to validate.

public class Status { public const string NOT_STARTED = "not started"; public const string IN_PROGRESS = "in progress"; public const string ON_HOLD = "on hold"; public const string COMPLETED = "completed"; public const string REFUSED = "refused"; public static string[] List = new string[] { NOT_STARTED, IN_PROGRESS, ON_HOLD, COMPLETED, REFUSED }; } class TestClass { static void Main(string[] args) { var newStatus = "new status" if (!Status.List.Contains(newStatus)) { // new status is not valid } if (newStatus == Status.IN_PROGRESS) { // new status in progress } } } 

Comments

0

I define Enum with underscore and replace when using later in code:

// Enum definition public enum GroupName { Major_Features, Special_Features, Graphical_Features }; // Use in code: internal Group GetGroup(GroupName groupName) { //... string name = groupName.ToString().Replace('_',' ')); //... }

Comments

0

What is your purpose of this question, if you want to have a set of strings, then you want to have a integer value for each of keys, the best way is using a Dictionary from your keys and values, like this:

Dictionary<string, int> MyDictionary = new Dictionary<string, int>() { {"good Boy", 1 }, {"Bad Boy", 2 }, }; 

Then you can give the integer value from the key like this:

int value = MyDictionary["good Boy"]; 

Comments

-1

You cannot have enum with spaces in .Net. This was possible with earlier versions of VB and C++ of course, but not any longer. I remember that in VB6 I used to enclose them in square brackets, but not in C#.

Comments

-1

Since the original question was asking for adding a space within the enum value/name, I would say that the underscore character should be replaced with a space, not an empty string. However, the best solution is the one using annotations.

Comments

-1

An enumerator cannot contain white space in its name.

As we know that enum is keyword used to declare enumeration.

you can check throw this link https://msdn.microsoft.com/en-us/library/sbbt4032.aspx

Comments

-1

You can write the spaced word in brackets. Then define a constructor to take up the values inside the bracket. As given below

public enum category { goodBoy("Good Boy"), BadBoy("Bad Boy") } private String categoryType; category(String categoryType) { this.categoryType = categoryType; } 

Comments