71

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

love thakker
  • 460
  • 2
  • 13
  • 29

19 Answers19

104

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()
Austin
  • 2,203
  • 3
  • 12
  • 28
Luke T O'Brien
  • 2,565
  • 3
  • 26
  • 38
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";
Soviut
  • 88,194
  • 49
  • 192
  • 260
  • On my enum "Good_Boy"set but on my control i want to replace _ with Space how to do –  Jul 09 '09 at 05:23
  • 9
    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! – Soviut Jul 09 '09 at 06:04
  • 2
    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. – Veverke Nov 15 '16 at 14:08
18

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.

OrionMD
  • 389
  • 1
  • 7
  • 13
17
using System.ComponentModel;

then...

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

Solved!!

Xtian11
  • 2,130
  • 1
  • 21
  • 13
  • 15
    Please don't just code dump. Provide an explanation about it, such as *you can use attributes ... such as ... because ... example* – Jim Dec 01 '16 at 18:33
  • 2
    Upvoted this answer since I'm working in the context of Unity, and the DataAnnotations are not available. – vandijkstef Feb 04 '18 at 13:28
16

Think this might already be covered, some suggestions:

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

Community
  • 1
  • 1
Brendan Kowitz
  • 1,795
  • 10
  • 14
10

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

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
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

Veverke
  • 9,208
  • 4
  • 51
  • 95
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.

donmezburak
  • 159
  • 1
  • 13
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"

JordanGW
  • 174
  • 1
  • 12
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.

Smac
  • 391
  • 2
  • 10
  • 28
  • Are you using the reference System.ComponentModel.DataAnnotations; – Smac Nov 06 '18 at 11:27
  • 1
    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? – jay-danger Apr 08 '19 at 17:47
  • 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... – Veverke May 16 '19 at 14:21
  • @jshockwave, you could make an extension method for that. I've posted an example with that. Hope it helps. – OrionMD Aug 29 '19 at 19:55
  • 3
    `.ToDescription()` doesn't seem to exist. Perhaps this is referring to the code from [this answer](https://stackoverflow.com/a/8387201/429949)? – Richard Marskell - Drackir Oct 16 '19 at 16:45
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

trinalbadger587
  • 1,905
  • 1
  • 18
  • 36
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
Rakesh Raut
  • 183
  • 3
  • 12
0

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
        }
    } 
}
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('_',' '));
    //...
}
mvs314
  • 1
  • 1
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"];
da jowkar
  • 181
  • 1
  • 8
-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#.

Cyril Gupta
  • 13,505
  • 11
  • 64
  • 87
-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.

-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

Devendra Gohel
  • 112
  • 1
  • 5
-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;
}
Ira Sinha
  • 21
  • 1
  • 6