Reputation: 59456
I am parsing some enum values from a text file. In order to simplify things I am using functions like the following:
(The sample code here uses C++/CLI but answers in C# are also welcome.)
bool TryParseFontStyle(String ^string, FontStyle% style){
try {
FontStyle ^refStyle = dynamic_cast<FontStyle^>(
Enum::Parse(FontStyle::typeid, string));
if(refStyle == nullptr)
return false;
style = *refStyle;
return true;
}
catch(Exception ^e){
return false;
}
}
Now I need to rewrite similar functions for each enum type that I am parsing. How do I use generics to write one single function to handle any enum type?
Update: Found a similar question here: How to TryParse for Enum value?
Upvotes: 0
Views: 839
Reputation: 8259
In c#:
Enum.Parse(typeof(yourEnum),"yourValue");
Just surround that with a try catch and your set to go
Upvotes: 0
Reputation: 20056
public static bool TryParseEnum<T> (string value, out T result) where T : struct
{
if (value == null)
{
result = default (T) ;
return false ;
}
try
{
result = (T) Enum.Parse (typeof (T), value) ;
return true ;
}
catch (ArgumentException)
{
result = default (T) ;
return false ;
}
}
Upvotes: 1
Reputation: 41909
This method seems to work and does not use try/catch.
public static bool EnumTryParse<T>(string strType,out T result)
{
string strTypeFixed = strType.Replace(' ', '_');
if (Enum.IsDefined(typeof(T), strTypeFixed))
{
result = (T)Enum.Parse(typeof(T), strTypeFixed, true);
return true;
}
else
{
foreach (string value in Enum.GetNames(typeof(T)))
{
if (value.Equals(strTypeFixed, StringComparison.OrdinalIgnoreCase))
{
result = (T)Enum.Parse(typeof(T), value);
return true;
}
}
result = default(T);
return false;
}
}
Upvotes: 0