I've read a few articles recently regarding the use of strings with enums - discussing how to access the constant name values or how to set a variable with the correct value when you only have a string value (enum constant name) - and all present somewhat convoluted ways of achieving this.
I'm guessing the authors are not aware that the .Net framework provides methods for this - out the box.
Hopefully the following code shows how to do this.
private enum CarTypes
{
Lotus = 0,
Morgan = 1,
Atom = 2
}
private void button1_Click(object sender, EventArgs e)
{
CarTypes myCarType = CarTypes.Morgan;
textBox1.Text = Enum.GetName(typeof(CarTypes), myCarType) + ", " + myCarType.ToString() + ", " + (myCarType==CarTypes.Morgan).ToString();
myCarType = (CarTypes)Enum.Parse(typeof(CarTypes), "Atom");
textBox1.Text += "\r\n" + Enum.GetName(typeof(CarTypes), myCarType) + ", " + myCarType.ToString() + ", " + (myCarType == CarTypes.Atom).ToString();
myCarType = (CarTypes)Enum.Parse(typeof(CarTypes), "loTus", true);
textBox1.Text += "\r\n" + Enum.GetName(typeof(CarTypes), myCarType) + ", " + myCarType.ToString() + ", " + (myCarType == CarTypes.Lotus).ToString();
}
Output:
Morgan, Morgan, True
Atom, Atom, True
Lotus, Lotus, True
*** Update ***
For those wanting to know how to get the enum type based on the integer value, you can simply cast it eg:
int carTypeInteger = 1;
CarTypes carType = (CarTypes)carTypeInteger;
carType would be set to Morgan
and visa-versa:
int carTypeInteger = (int)CarTypes.Morgan;
carTypeInteger would be set to 1
Simple stuff
Tim