Reputation: 3555
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.
Upvotes: 14
Views: 18781
Reputation: 12606
If what is displaying the enum text is aware of (and utilizes) the System.ComponentModel namespace, then you can decorate the enum with the System.ComponentModel.DescriptionAttribute and type the lowercase version in yourself.
If you are directly getting the string value, you can still do this, though the overhead of you writing the reflection code may be more than you want to deal with.
HTH, Brian
Upvotes: 1
Reputation: 56717
You might also use Enum.GetNames(...)
to get a string array containing the enum values. Then, convert these to lower case. To convert from string to the respective enum value you can use the Enum.Parse
method passing true
in the third parameter, which makes the comparison case insensitive.
Upvotes: 0
Reputation: 54764
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
Upvotes: 2
Reputation: 61467
No, there isn't except for an extension method on object
.
public static string ToLower (this object obj)
{
return obj.ToString().ToLower();
}
Upvotes: 15