Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum ToString appears as a number

Tags:

c#

enums

tostring

I have an enum

private enum TimeUnit
{      
  Day,
  Month,
  Year
}

And I'm populating a description with:

return string.Concat(unit, "(s)");

Where unit is a TimeUnit. Most of the time this works fine and displays "Days(s)" however on a particular server it's displaying as "1(s)"

What would cause this?

like image 692
Liath Avatar asked Feb 27 '13 12:02

Liath


People also ask

Can you toString an enum?

The Java Enum has two methods that retrieve that value of an enum constant, name() and . toString(). The toString() method calls the name() method which returns the string representation of the enum constant.

How do you find the enum value of a string?

Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

Can we convert enum to string in C#?

We can convert an enum to string by calling the ToString() method of an Enum.

How do I find the enum name?

Enum. GetName(Type, Object) Method is used to get the name of the constant in the specified enumeration that has the specified value. Syntax: public static string GetName (Type enumType, object value);


2 Answers

Try using Enum.GetName()

it also has the advantage of being safer since it requires:

  • The value you passed in isn't null.
  • The value you passed in is of a type that an enumeration can actually use as it's underlying type, or of the type of the enumeration itself. It uses GetType on the value to check this.
like image 194
happygilmore Avatar answered Oct 10 '22 06:10

happygilmore


You should format appropriately using ToString:

return string.Concat(unit.ToString("F"), "(s)");
like image 34
Grant Thomas Avatar answered Oct 10 '22 06:10

Grant Thomas