2

Given the C# enum:

public enum options: byte
{
    yes = 0,
    no = 22,
    maybe = 62,
    foscho = 42
}

How do you retrieve the String 'maybe' if given the byte 62?

yesman
  • 7,165
  • 15
  • 52
  • 117
  • possible duplicate of [Enum value to string](http://stackoverflow.com/questions/3120436/enum-value-to-string) – dandan78 Nov 04 '14 at 10:16
  • possible duplicate of [Cast int to enum in C#](http://stackoverflow.com/questions/29482/cast-int-to-enum-in-c-sharp) – Carbine Nov 04 '14 at 10:18

2 Answers2

8

You can cast it to enum and retreive by ToString():

var result = ((options)62).ToString();
  • 1
    Works, but please don't do it this way. This is bad-practice, don't teach yourself bad-practice. Exceptions will be thrown when a specific value doesn't match the enum. You should use Enum.GetName or Enum.TryParse. – It's me ... Alex Nov 04 '14 at 10:41
  • @It'sme...Alex nope - no exception will be thrown - the int value will be returned, when there is no matching enum value. –  Nov 04 '14 at 10:45
  • WTF?! You're right ... this is Sooooo bad. Casting a non-existing value to an enum actually works. Don't know whether this is behavior that everyone likes ... I dont. For me it would be one more reason to prefer GetName (or TryParse when a values comes in as a string) above casting – It's me ... Alex Nov 04 '14 at 10:57
  • Yeah - it's good interview question - "What happens if you cast int to non-existing enum value?" :) –  Nov 04 '14 at 11:03
4

var stringValue = Enum.GetName(typeof(options), 62); // returns "maybe"

Which you might also want to wrap in a check:

if (Enum.IsDefined(typeof(options), 62))
{
    var stringValue = Enum.GetName(typeof(options), 62);    // returns "maybe"`
}

MSDN link

awj
  • 7,482
  • 10
  • 66
  • 120