Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the lowercase representation of an enum in C#?

Tags:

c#

.net

enums

I have the following enum in an ASP.NET MVC application, and I want to use that enum as a parameter. To do so, I'd like to to return the lowercase string representation of that enum.

 public enum SortOrder
 {
      Newest = 0,
      Rating = 1, 
      Relevance = 2 
 }

How can I get the lowercase representation of an enum in C#? I'd like for the enums to retain their natural titlecase representation as well.

like image 998
Radu D Avatar asked Dec 09 '10 13:12

Radu D


2 Answers

No, there isn't except for an extension method on object.

public static string ToLower (this object obj)
{
  return obj.ToString().ToLower();
}
like image 146
Femaref Avatar answered Oct 15 '22 15:10

Femaref


Is there any way to get the string in lower case exceptiong: value.ToString().ToLower() ?

No (unless you change the enum: newest, rating, relevance...)

A common technique is to add an attribute against each enum member, specifying the string that you want to associate with it, For instance: http://weblogs.asp.net/grantbarrington/archive/2009/01/19/enumhelper-getting-a-friendly-description-from-an-enum.aspx

like image 25
Tim Robinson Avatar answered Oct 15 '22 17:10

Tim Robinson