0

I need my enum to return a formatted string to the view, for example:

public enum status
{ 
   NotStarted,
   InProgress,
} 

return: Not Started and In Progress. How I do it? Thanks (language C#)

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • 1
    Have a look here: http://stackoverflow.com/questions/479410/enum-tostring-with-user-friendly-strings – mshsayem Nov 25 '15 at 15:48
  • I've just added my [answer](http://stackoverflow.com/questions/479410/enum-tostring-with-user-friendly-strings/33921043#33921043) to linked question, which is nice example of [Humanizer](https://github.com/Humanizr/Humanizer) usage. – Konrad Kokosa Nov 25 '15 at 16:01

3 Answers3

2

enums don't do that. You'd need to provide a map of enum values to display strings or you could do something like define an attribute with a display string that you can use (which requires some fiddly reflection to get the attribute for a given enum value, but has the advantage that you can define the display name right where you define the enum value).

For example, you can use a Dictionary<status,string> to map them:

var myMap = new Dictionary<status,string>()
{
    { status.NotStarted, "Not Started" },
    { status.InProgress, "In Progress" }
};

Now to get the display string for a given status value s you'd just do something like:

var s = status.NotStarted;
var displayString = myMap[s];   // "Not Started"

Of course, you'd put this in a class somewhere so it's only defined once in one place.

Another rather brittle, quick-and-dirty way to do it would be to exploit the fact that your enum names are Pascal-cased and use something like a regex to take the enum name and insert an extra space. But that's pretty hacky. So you could do something like:

var r = new Regex("([A-Z][a-z]*)([A-Z][a-z]*)");
var displayString = r.Replace(s.ToString(),"$1 $2");    // "Not Started"

But that would choke on any enum values that didn't fit the pattern of two Pascal-cased words. Of course, you could make your regex more flexible, but that's beyond the scope of the question.

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
1

Calling ToString on an emum value is the equivalent to Enum.GetName which would give you the named value i.e.

Console.WriteLine(status.NotStarted.ToString()) // NotStarted

From there, assuming the format is consistent, you could convert the string from Pascal casing to a whitespace separated string e.g.

string result = Regex.Replace(status.NotStarted, "([a-z])([A-Z])", "$1 $2");
Console.WriteLine(result); // Not Started

See example.

James
  • 80,725
  • 18
  • 167
  • 237
0
Enum.GetName(typeof (Status), Status.InProgress));
Sergei G
  • 1,550
  • 3
  • 24
  • 44