typeof(enum) as argument to method

G

Guest

Hi

I need to parse strings to enumerated types for several different
enumerated types. Im doing this for each of them, bu I wonder if there is a
way to write a generic method that also takes the specific enumerated type as
an argument. Is it possible to pass the typeof(enum) as an argument, and how
is it done? See current method below.

regards Jesper.


private static Week WeekFromStr(string str)
{
try
{
return (Week)Enum.Parse(typeof(Week), str);
}
catch ( Exception e )
{
throw new Exception("WeekFromStr error " + e.Message);

}

return Week.na;
}
 
M

Marc Gravell

How about:

private static T ParseEnum<T>(string value) {
return (T) Enum.Parse(typeof(T), value);
}

alternative (no generics):

private static object ParseEnum(Type type, string value) {
return Enum.Parse(type, value);
}

but note that then the caller must do both a cast and a typeof

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top