user2023861
user2023861

Reputation: 8208

How do I convert a char to a char-based Enum object?

I have this enum:

enum OptionalityEnum { call = 'C', put = 'P', undefined = 'N' }

Is there an easy way to turn a char into the enum type? This works:

char chOpt = 'C';
OptionalityEnum opt = (OptionalityEnum)chOpt; //opt = OptionalityEnum.call

But if my char is a value that doesn't exist in the enumeration, this produces weird results.

char chOpt = 'X';
OptionalityEnum opt = (OptionalityEnum)chOpt; //opt = 88

I know about some of the Enum functions, but I can't find one that does this conversion for me.

Enum.GetNames(typeof(OptionalityEnum)) = { call, na, put }
Enum.GetValues(typeof(OptionalityEnum)) = { call, na, put }
Enum.TryParse<OptionalityEnum>("C", out optionality) = false

Enum.TryParse<OptionalityEnum>("call", out optionality) = true 
  //... but that's not what I want.

Enum.IsDefined(typeof(OptionalityEnum), "call") = true
  //... but that's not what I want.

Do I need to write my own converter? Something like this?

private static OptionalityEnum Convert(char ch) { OptionalityEnum result = (OptionalityEnum)ch; if (Enum.IsDefined(typeof(OptionalityEnum), result)) return result; else return OptionalityEnum.undefined; }

private static bool TryConvert(char ch, out OptionalityEnum opt)
{
    opt = (OptionalityEnum)ch;
    return Enum.IsDefined(typeof(OptionalityEnum), opt);
}

This works but it seems sloppy. I'd be surprised if something like this doesn't already exist.

EDIT: I originally used a bad example for my Convert function. I changed it to the TryConvert function.

Upvotes: 0

Views: 190

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500695

Your "sloppy" solution seems entirely appropriate to me. There's nothing else which is going to default to "undefined" for you. Using the conditional operator would make it slightly cleaner:

private static OptionalityEnum Convert(char ch)
{
    OptionalityEnum result = (OptionalityEnum)ch;
    return Enum.IsDefined(typeof(OptionalityEnum), result)
        ? result : OptionalityEnum.undefined;
}

EDIT: For the TryConvert method, I'd actually make sure that you set opt to default(OptionalityEnum) if it doesn't exist.

But no, I don't believe this exists in the framework. However, you might want to look at my Unconstrained Melody project where you could at least use the IsNamedValue extension method, which would avoid boxing.

Upvotes: 2

Related Questions