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
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
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.
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()
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";
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.
using System.ComponentModel;
then...
public enum category
{
[Description("Good Boy")]
goodboy,
[Description("Bad Boy")]
badboy
}
Solved!!
Think this might already be covered, some suggestions:
Just can't beat stackoverflow ;) just sooo much on here nowdays.
That's not possible, an enumerator cannot contain white space in its name.
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:
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.
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"
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.
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
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
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
}
}
}
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('_',' '));
//...
}
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"];
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#.
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.
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
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;
}