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 th
Have a read of this tutorial to understand how enums work. There are examples of switch
statements too.
Enumerations cannot be of string type.
The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
http://msdn.microsoft.com/en-us/library/sbbt4032.aspx
Just sharing my solution. By downloading the nuget package Extension.MV, a method is available for getting the string from a Enum Description
public enum Prefix
{
[Description("doctor")]
doctor = 1,
[Description("mr")]
mr = 2,
[Description("mrs")]
mrs = 3
}
public static class PrefixAdapter {
public static string ToText(this Prefix prefix) {
return prefix.GetEnumDescription();
}
public static Prefix ToPrefix(this string text) {
switch (text)
{
case "doctor"
return Prefix.doctor;
case "mr"
return Prefix.mr;
case "ms"
return Prefix.mrs;
}
}
}
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
}
Why not to use just pure enum and switches?
enum Prefix
{
doctor,
mr,
mrs
}
Then you can use is like
string case = "doctor";
switch ((Prefix)Enum.Parse(typeof(Prefix), "doctor"))
{
case Prefix.doctor:
...
break;
...
default:
break;
}
I believe the standard way to do this is to use a static class with readonly string properties that return the value you want.