I had a problem where I needed to get an Enum, but all I had to work from was a string value of that Enum.
I’m not sure this is the best way to convert a string to an Enum. And that is one reason why I wanted to post this on my blog, so others could provide feedback and ideas. The other reason is so others can learn from what we know (and I’ll have it somewhere for the next time I need it ).
There is two pieces of useful information below. One is the Enum.Parse() method exists. And the other is a neat trick to get around having to deal with Enum.Parse()’s Type parameter.
Note: the method and the extension method will work in later versions of .NET and .NET Compact Framework.
Show me the method:
1: public static T StringToEnum<T>(this string name)
2: {
3: return (T)Enum.Parse(typeof(T), name, true);
4: }
Chublogga, one of our readers, asked could the StringToEnum method be made into an extension method. It can, see below.
Show me the extension method:
1: using System;
2: using System.Linq;
3: using System.Collections.Generic;
4: using System.Text;
5: using System.Text.RegularExpressions;
6:
7: namespace CraftExtensions
8: {
9: public static class CraftExtensions
10: {
11: public static T StringToEnum<T>(this string name)
12: {
13: return (T)Enum.Parse(typeof(T), name, true);
14: }
15: }
16: }
Theme design by Jelle Druyts
Pick a theme: BlogXP BlogXP business calmBlue Candid Blue dasBlog dasblogger DirectionalRedux Discreet Blog Blue Elegante essence Just Html MadsSimple Mobile Mono Movable Radio Blue Movable Radio Heat nautica022 orangeCream Portal Project84 Project84Grass Slate Sound Waves The Right Stuff 2.0 Tricoleur useit.com Voidclass2 BlogXP BlogXP business calmBlue Candid Blue dasBlog dasblogger DirectionalRedux Discreet Blog Blue Elegante essence Just Html MadsSimple Mobile Mono Movable Radio Blue Movable Radio Heat nautica022 orangeCream Portal Project84 Project84Grass Slate Sound Waves The Right Stuff 2.0 Tricoleur useit.com Voidclass2
Powered by: newtelligence dasBlog 2.0.7226.0
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2009, Chris Craft
E-mail