loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 



Advertise Here
C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

Parsing Strings to Enums with a Simple Univeral Extension

by naspinski 10/29/2009 4:24:00 AM

getting an enum to a string is easy, but switching back can be a pain

If I have an enum:
public enum WhatToShow { All, Courses, Seminars };

and I want to turn a string "Courses" back into that enum Type, there are a few ways I could do it. The most basic way would be to use a switch statement; that is a pain, especially for large enums, plus it has to be re-written for each enum. Here is a simple extension you can use to convert strings back into enums:
public static T ToEnum<T>(this string strOfEnum)
{
    return (T)Enum.Parse(typeof(T), strOfEnum);
}

Now if I have a simple string, it is simple to turn it back to an enum:
string str = "Courses";
WhatToShow en = str.ToEnum<WhatToShow>();

Currently rated 4.0 by 4 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

c#

Related posts

Comments

10/29/2009 8:51:47 PM

John Varga
I believe your extension is slightly incorrect, should be

public static T ToEnum<T>(this string str)
{
return (T)Enum.Parse(typeof(T), str);
}

John Varga us

10/30/2009 1:28:13 PM

naspinski
You just re-typed the extension and changed the variable name... am I missing something?

naspinski us

11/5/2009 2:23:53 AM

naspinski
Ahh, you're right, forgot to replace the brackets in html... browser thought it was an element.

naspinski us


Comments are closed