Using strings and enum in C#

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();


Morgan, Morgan, True
Atom, Atom, True
Lotus, Lotus, True

About Saad Khan

Saad is an ASP.NET developer with 4 years of experience, and has also made a number of contributions to the Sitefinity marketplace and community. He loves to explore new code, and create innovative tools and procedures while exploring new approaches in his work with Sitefinity and MVC. As an experienced .NET developer, he frequents both Telerik and Microsoft technologies. In his spare time, Saad is an avid gamer and movie fanatic, and also experiments with new and interesting tools on the Microsoft platform.​​

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: