jumpingcode jumpingcode - 20 days ago 7
C# Question

How to assign string values to enums and use that value in a switch

Basically a series of titles will be passed into the switch statement and I need to compare them against the string values of the enum. But I have little to no idea how to do this correctly.

Also, I don't know if this is even the best approach so if anyone has any ideas?

For example:

enum
{
doctor = "doctor",
mr = "mr",
mrs = "mrs"
}


and then switch through the string values I've assigned them.

Answer

You can't have an enum with an underlying type of string. The underlying type can be any integral type except char.

If you want to translate a string to your enum then you'll probably need to use the Parse or TryParse methods.

string incoming = "doctor";

// throws an exception if the string can't be parsed as a TestEnum
TestEnum foo = (TestEnum)Enum.Parse(typeof(TestEnum), incoming, true);

// try to parse the string as a TestEnum without throwing an exception
TestEnum bar;
if (Enum.TryParse(incoming, true, out bar))
{
    // success
}
else
{
    // the string isn't an element of TestEnum
}

// ...

enum TestEnum
{
    Doctor, Mr, Mrs
}
Comments