Earlier, we posted a tutorial on how to get an enum from anumber.
In this tutorial we're going to show you how to use a similar technique
to get an enum from a string.
Just like last time I'm going to create a generic method for converting
the string to an enum. This lets us convert to any type of enum using a
single method.
public static T StringToEnum(string name) { return
(T)Enum.Parse(typeof(T), name); }
The code to actually get an enum from a string is very simple thanks to
.Net's Enum class. All we have to do is call
Parse
, passing in the
type of enum and the string. Since Parse
returns an object, we need to
cast it to our desired type.
Let's see how to use this function using some examples.
public enum DaysOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
public enum MonthsInYear
{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}
DaysOfWeek d = StringToEnum<DaysOfWeek>("Monday");
//d is now DaysOfWeek.Monday
MonthsInYear m = StringToEnum<MonthsInYear>("January");
//m is now MonthsInYear.January
So what happens if you enter a string value that doesn't correspond to
an enum? The
Enum.Parse
will fail with an ArgumentException
.DaysOfWeek d = StringToEnum<DaysOfWeek>("Katillsday");
//throws an ArgumentException
//Requested value "Katillsday" was not found.
We can get around this problem by first checking that the enum exists
using
Enum.IsDefined
.if(Enum.IsDefined(typeof(DaysOfWeek), "Katillsday"))
StringToEnum<DaysOfWeek>("Katillsday");
That about does it for converting a string to a enum using .NET and C#.
If you have any comments or questions, let me know.
Comments
Post a Comment